使用Spring @Configuration批注注入bean列表 [英] Inject a list of beans using Spring @Configuration annotation

查看:689
本文介绍了使用Spring @Configuration批注注入bean列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Spring bean,在Spring Bean中我依赖于其他bean的列表。我的问题是:如何将bean的通用列表注入该bean的依赖项?

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?

例如,一些代码:

public interface Color { }

public class Red implements Color { }

public class Blue implements Color { }

我的豆子:

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();
  }
}

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

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?

感谢您的帮助!

推荐答案

你有什么应该工作,有一个 @Resource @Autowired < setter上的/ code>应该将所有Color实例注入 List< Color> 字段。

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

如果你想更明确,你可以将一个集合作为另一个bean返回:

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.

这篇关于使用Spring @Configuration批注注入bean列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆