Search code examples
javaspringspring-bean

How to combine beans with the same type into an array by using annotations only?


I have several beans:

@Bean
public MyBean myBean1(){
    return new MyBean(1);
}

@Bean
public MyBean myBean2(){
    return new MyBean(2);
}

@Bean
public MyBean myBean3(){
    return new MyBean(3);
}

I would like to combine them into one collection and pass as an argument. Something like:

@Bean
public MyFinalBean myFinalBean(Collection<MyBean> myBeans){
    return new MyFinalBean(myBeans);
}

Is there a possibility to combine beans with annotations only? I.e. without using a separate method with applicationContext.getBeansOfType(MyBean.class);?


Solution

  • Spring is able to autowire all beans implementing the same interface into one collection of that interface. The following code works correctly:

    @Bean
    public MyFinalBean myObject(List<MyBean> lst) {
        return new MyFinalBean(lst);
    }