[英]How to create multiple beans of same type according to configuration in Spring?
I'm trying to create a specified number of beans of a same type in Spring. 我正在尝试在Spring中创建指定数量的相同类型的bean。
I've tried: 我试过了:
@Bean(name = "beanList")
public List<MyBean> beanList(
@Value("${number:1}") int number
) {
List<MyBean> beanList = new ArrayList<>(number);
for (int i = 0; i < number; i++) {
beanList.add(new MyBean());
}
return beanList;
}
But this is not what expected. 但这不是预期的。
In this way, the bean "beanList" is maintained by spring context, instead of it's elements, so I can't specify a name and init method or destroy method for each element in the list. 这样,bean“ beanList”是由spring上下文维护的,而不是它的元素,因此我无法为列表中的每个元素指定名称和init方法或destroy方法 。
Any ideas? 有任何想法吗?
You could have a look at BeanFactoryPostProcessor , I tried with following code and it's working just fine, Bean
s depends on MyBean
could also be autowire
d: 您可以看一下BeanFactoryPostProcessor ,我尝试使用以下代码,它的工作正常, Bean
取决于MyBean
也可以是autowire
d:
@Configuration
public class AppConfig implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
for (int i = 0; i < 3; i++) {
System.out.println("register my bean: " + i);
beanFactory.registerSingleton("bean-" + i, new MyBean("MyBean-" + i));
}
}
}
Since you have complete control of creation process of MyBean
instance, you can simply pass other beans in through constructor if it's necessary. 由于您可以完全控制MyBean
实例的创建过程,因此可以根据需要简单地将其他bean传递给构造函数。 Hope this could be helpful to you :-) 希望这对您有所帮助:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.