List beans with Spring @Configuration annotation

I have a Spring bean, and in Spring Bean I have a dependency on a list of other beans. My question is: how can I insert a generic list of beans as a dependency on this 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 a list of colors in Painter? Also, on the side of the note: should I @Configuration return an interface type or class?

Thanks for the help!

+7
source share
1 answer

That you should work with @Resource or @Autowired in the setter should introduce all instances of Color in the List<Color> field.

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

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

and use it as an autoset field like this:

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

OR

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

The question of returning an interface or implementation needs to work, but the interface should be preferred.

+12
source

All Articles