Search code examples
springspring-bootspring-mvcweb-configfreemarker

How to create List of beans from existing beans in Spring


I am migrating an old Spring project to SpringBoot. The old project has XML based configurations.

I have a list of beans declaration in the old config as below:

<bean id="basic" class="com.xyz.Parameter" abstract=true>
</bean>

<!-- List -->
<util:list id="searches">
    <bean parent="basic" id="roles">
        <property name="name" value="abc">
        ...
        ...
     </bean>
    <bean parent="basic" id="simple">
        <property name="name" value="abc">
        ...
        ...
     </bean>
    <bean parent="basic" id="user">
        <property name="name" value="abc">
        ...
        ...
     </bean>
</util:list>

Now, in the Java configuration file, I am doing as below:

@Configuration
class WebConfig{
    
    @Bean ("Basic")
    public Parameter basic(){
        return Parameter.builder ()
            .format (Pattern.compile("^ [A-Za-20-9]")
            .maxLength (100) build();
    }

    @Bean
    public Parameter simple (@Qualifier ("Basic") Parameter basic){
        return basic.toBuilder ()
            .field ("attribute")
            .Label ("Attribute Nane").build();
    }

    @Bean
    public Parameter user(@Qualifier ("Basic") Parameter basic){
        Parameter product = basic. toBuilder ()
            .field ("product")
            .label ("Product").build();
    }

    
    //TODO: List implementation
    @Bean("searches")
    public List< Parameter> getSearch(){
        
        return List.of(user()); //It requires params
    }

}

The plan is to compile a list of all the beans and utilize it as a @Resource whenever it is needed.

So, what is the best technique to build a list of beans? Should I use the BeanFactory to retrieve the beans and add them to the list instead of calling each bean function individually?


Solution

  • After declaring multiple beans of same type, you can just @Autowired List<MyBean> myBeans; or @Autowired Map<String, MyBean> myBeans; where map key is a bean name.

    @Autowired is just as an example here, any Spring injection type works.