8

I've got a Spring bean, and in the Spring Bean I have a dependency on a list of other beans. My question is: how can I inject a Generic list of beans as a dependency of that bean?

For example, some code:

public interface Color { }

public class Red implements Color { }

public class Blue implements Color { }

My bean:

public class Painter {
  private List<Color> colors;

  @Resource
  public void setColors(List<Color> colors) {
      this.colors = colors;
  }
}

@Configuration
public class MyConfiguration {

  @Bean
  public Red red() {
    return new Red();
  }

  @Bean
  public Blue blue() {
    return new Blue();
  }

  @Bean
  public Painter painter() {
    return new Painter();
  }
}

The question is; how do I get the list of colors in the Painter? Also, on a side note: should I have the @Configuration return the Interface type, or the class?

Thanks for the help!

Erik Pragt
  • 13,513
  • 11
  • 58
  • 64
  • Possible duplicate of [Auto-wiring a List using util schema gives NoSuchBeanDefinitionException](http://stackoverflow.com/questions/1363310/auto-wiring-a-list-using-util-schema-gives-nosuchbeandefinitionexception) – gstackoverflow Nov 03 '15 at 19:11

1 Answers1

16

What you have should work, having a @Resource or @Autowired on the setter should inject all instances of Color to your List<Color> field.

If you want to be more explicit, you can return a collection as another bean:

@Bean
public List<Color> colorList(){
    List<Color> aList = new ArrayList<>();
    aList.add(blue());
    return aList;
}     

and use it as an autowired field this way:

@Resource(name="colorList") 
public void setColors(List<Color> colors) {
    this.colors = colors;
}

OR

@Resource(name="colorList")
private List<Color> colors;

On your question about returning an interface or an implementation, either one should work, but interface should be preferred.

Radek Postołowicz
  • 4,506
  • 2
  • 30
  • 47
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125
  • Hi Biju, thanks for the answer. I also thought it would work, but a colleague said that when deploying, Spring threw exceptions. I will investigate that a bit more. In the meantime, I've used a similar approach as the one you suggested. – Erik Pragt Feb 15 '13 at 12:49
  • Perfect! Just what I was looking for! – Flyingcows00 Sep 03 '14 at 16:42
  • Is there a way to inject the list into another `@Bean` method? Apparently `List` is awkward to inject by name. Recommendations are to use `@Resource` but this doesn't work as a method param. – Stewart Mar 06 '17 at 11:46