[英]How to create MULTIPLE beans based upon value in properties file
I want to create multiple beans based upon the value in configuration file.我想根据配置文件中的值创建多个 bean。 I have the bean ready in configuration file.
我在配置文件中准备好了 bean。 But how can I create multiple beans.
但是我怎样才能创建多个bean。
My current configuration file.我当前的配置文件。
@Configuration
public class JMSConfig {
@Bean
public DefaultMessageListenerContainer listenerContainers() {
...
}
}
My idea to achieve the requirement.我的想法达到要求。 If I use prototype scope I will get a new bean each time I ask for that bean.
如果我使用原型作用域,每次我请求那个 bean 时我都会得到一个新 bean。 So I added prototype.
所以我添加了原型。
@Configuration
public class JMSConfig{
@Value("${value}")
private long value;
@Bean
@Scope("prototype")
public DefaultMessageListenerContainer listenerContainers() {
.....
}
for(i = 0; i < value; i++){
//get a new bean
}
}
The important challenge I am facing is我面临的重要挑战是
If you want to get your beans right out from the Spring-Boot main
method.如果您想从 Spring-Boot
main
方法中直接获取 bean。 Use smth like this:像这样使用 smth:
@SpringBootApplication
public class MyApplication {
public static void main(final String[] args) {
ApplicationContext context = SpringApplication.run(MyApplication.class, args);
final int totalBeans = context.getEnvironment().getProperty("totalBeans")
final List<DefaultMessageListenerContainer> beans = new ArrayList<>();
for (int i = 0; i < totalBeans; i++) {
beans.add(context.getBean(DefaultMessageListenerContainer.class));
}
}
}
beans
list in this particular example contains N objects of DefaultMessageListenerContainer.class
.这个特定示例中的
beans
列表包含DefaultMessageListenerContainer.class
N 个对象。
"totalBeans" argument in getProperty
method is the name of appropriate property in application.yml
file, defining N total count of beans. getProperty
方法中的“totalBeans”参数是application.yml
文件中相应属性的名称,定义了 N 个 bean 的总数。
BTW: It might be better not to create beans from main
method (if it is not a mandatory requirement):顺便说一句:最好不要从
main
方法创建 bean(如果它不是强制性要求):
In this case, you can define List<DefaultMessageListenerContainer>
bean in your @Configuration
class and inject it later using standard Spring approach:在这种情况下,您可以在
@Configuration
类中定义List<DefaultMessageListenerContainer>
bean,然后使用标准 Spring 方法注入它:
@Value("totalBeans")
private int totalBeans;
@Bean
public List<DefaultMessageListenerContainer> beans() {
final List<DefaultMessageListenerContainer> beans = new ArrayList<>();
for (int i = 0; i < totalBeans; i++) {
beans.add(new DefaultMessageListenerContainer());
}
return beans;
}
...
@Autowired private List<DefaultMessageListenerContainer> beans;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.