简体   繁体   English

使用Spring @Configuration批注注入bean列表

[英]Inject a list of beans using Spring @Configuration annotation

I've got a Spring bean, and in the Spring Bean I have a dependency on a list of other beans. 我有一个Spring bean,在Spring Bean中我依赖于其他bean的列表。 My question is: how can I inject a Generic list of beans as a dependency of that bean? 我的问题是:如何将bean的通用列表注入该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? 如何获取Painter中的颜色列表? Also, on a side note: should I have the @Configuration return the Interface type, or the class? 另外,在旁注:我应该让@Configuration返回接口类型,还是类?

Thanks for the help! 谢谢您的帮助!

What you have should work, having a @Resource or @Autowired on the setter should inject all instances of Color to your List<Color> field. 你有什么应该工作,在setter上有@Resource@Autowired应该将所有Color实例注入List<Color>字段。

If you want to be more explicit, you can return a collection as another bean: 如果您想更明确,可以将集合作为另一个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. 关于返回接口或实现的问题,任何一个都应该工作,但接口应该是首选。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM