java 使用 Spring @Configuration 注解注入 bean 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14892757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 17:44:56  来源:igfitidea点击:

Inject a list of beans using Spring @Configuration annotation

javaspringspring-annotations

提问by Erik Pragt

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?

我有一个 Spring bean,在 Spring Bean 中,我依赖于其他 bean 的列表。我的问题是:如何将 Generic 的 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? Also, on a side note: should I have the @Configuration return the Interface type, or the class?

问题是; 如何获取 Painter 中的颜色列表?另外,附带说明:我应该让@Configuration 返回接口类型还是类?

Thanks for the help!

谢谢您的帮助!

回答by Biju Kunjummen

What you have should work, having a @Resourceor @Autowiredon the setter should inject all instances of Color to your List<Color>field.

你所拥有的应该可以工作,在二传手上有一个@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.

关于返回接口或实现的问题,任何一个都应该工作,但接口应该是首选。