Reputation: 179
I'm trying to create a specified number of beans of a same type in Spring.
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.
Any ideas?
Upvotes: 9
Views: 17888
Reputation: 12501
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:
@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. Hope this could be helpful to you :-)
Upvotes: 12