Menu

Creating collection of Spring Beans

Some times there might arise situations where you want to create a number of Spring Beans, but you don’t know how many beans are there at coding time.

Usually, you create a Spring bean as follows:

But what if you want to create 50 such beans which differ only in the argument supplied to the constructor? Or a similar case arise where the number of beans to be created cannot be determined at coding time? In such cases, we can create the bean definitions and add the beans to Spring container at runtime using BeanFactoryPostProcessor.

Implement BeanFactoryPostProcessor in either a @Configuration file or a @Component bean(make sure this bean gets scanned and created).

If there are more than one constructor arguments, the call can be chained as follows:

All this works fine when you have to create a bean using constructor. But 😦 I haven’t figured out how to do this when we use a chain of factory methods to create a bean as follows: