简体   繁体   English

从应用程序属性创建Spring原型bean

[英]Create spring prototype beans from application properties

I want to create N beans based on a list of values defined in application.properties 我想基于application.properties中定义的值列表创建N个bean

eg 例如

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

I would have a list in application.properties as 我将在application.properties中有一个列表

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

How do I create beans (in this case, 2) and then use them arbitrarily when required? 如何创建bean(在这种情况下为2),然后在需要时任意使用它们? eg 例如

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

BTW. 顺便说一句。 I intend to use annotations. 我打算使用注释。

I would implement this with an kind of factory. 我会用一种工厂来实现。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM