How to inject several beans with Spring Java config?

798 views Asked by At

Given spring java-config with method that returns list of beans:

@Configuration
public class Config {

    @Bean(name = "resultConsumers")
    public List<Consumer> getConsumers() {
        return Arrays.asList(...);
    }
}

How can I inject it in another bean?

class Bean {

   @Inject
   what?
}

P.S. It is not list with different implementations of consumers, they are all instances of the same class.

3

There are 3 answers

0
maframaran On
    @Configuration
public class Config {

    @Bean
    public List<Consumer> getConsumers() {
        return Arrays.asList(...);
    }
}

And the injection is like this

    class InjectionPoint{

   @Autowred
   private Consumer [] consumerList;
}

And that's all.

1
hyness On

You should not create the @Bean as a list. Simply add all of your Consumer objects as individual beans. Autowire a field as a List of Consumers, and Spring will find all of your Consumer beans and create the List for you...

@Configuration
public class Config {

    @Bean
    public Consumer consumer1() {
        return new Consumer();
    }

    @Bean
    public Consumer consumer2() {
        return new Consumer();
    }
}
...
class Bean {

    //  Contains consumer1 and consumer2
    @Inject
    private List<Consumer> consumers;
 }
3
Sotirios Delimanolis On

When you annotate a Collection type with @Autowired, Spring doesn't look for a corresponding bean of that type. Instead it looks for the component type that the Collection is meant to store.

Instead, use @Resource with the bean name.

@Resource(name ="resultConsumers")
private List<Consumer> consumers;