【问题标题】:Create spring prototype beans from application properties从应用程序属性创建 spring 原型 bean
【发布时间】:2023-03-29 15:40:01
【问题描述】:

我想根据 application.properties 中定义的值列表创建 N 个 bean

例如

MyBean {
    private String name; // with appropriate accessor methods
    MyBean(String n) {
        this.name = n;
    }
    public void saySomeThing() {
        log.debug(this.name+ " says hello");
    }
}

我会在 application.properties 中有一个列表

names[0]=James
names[1]=Mark

如何创建 bean(在本例中为 2),然后在需要时任意使用它们? 例如

for (int i=0;i<10;i++) {
    if (i%2==0)
        //get James to say hello
    else 
        //get Mark to say hello
}

顺便说一句。我打算使用注释。

【问题讨论】:

  • 我会用一种工厂来实现这个。
  • 谢谢。您如何建议我从配置文件中配置名称?还有,怎么使用?在我的用例中,我想创建 N 个 bean,然后稍后重用它们(就像在 for 循环中一样)。

标签: java spring prototype javabeans autowired


【解决方案1】:

我会用一种工厂来实现它。

@Bean
@Scope("prototype")
public MyBean myBean() {
    String name = ...
    return new MyBean(name);
}

【讨论】:

  • 实施了有点尴尬的解决方案。创建了一个配置类,它将所有名称(来自 application.properties)捕获为一个数组。然后使用工厂迭代数组并使用 context.getBean("myBean") 创建 bean。
猜你喜欢
  • 2021-03-02
  • 2018-06-18
  • 2015-12-14
  • 1970-01-01
  • 2021-09-03
  • 2012-04-12
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
相关资源
最近更新 更多