Juan Zhong
Juan Zhong

Reputation: 179

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.

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

Answers (1)

shizhz
shizhz

Reputation: 12501

You could have a look at BeanFactoryPostProcessor, I tried with following code and it's working just fine, Beans depends on MyBean could also be autowired:

@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

Related Questions