Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Spring@Configuration注释注入bean列表_Java_Spring_Spring Annotations - Fatal编程技术网

Java 使用Spring@Configuration注释注入bean列表

Java 使用Spring@Configuration注释注入bean列表,java,spring,spring-annotations,Java,Spring,Spring Annotations,我有一个Springbean,在Springbean中,我依赖于其他bean的列表。我的问题是:如何将bean的通用列表作为该bean的依赖项注入 例如,一些代码: public interface Color { } public class Red implements Color { } public class Blue implements Color { } 我的豆豆: public class Painter { private List<Color> col

我有一个Springbean,在Springbean中,我依赖于其他bean的列表。我的问题是:如何将bean的通用列表作为该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();
  }
}
公共类画师{
私有列表颜色;
@资源
公共无效设置颜色(列表颜色){
这个。颜色=颜色;
}
}
@配置
公共类MyConfiguration{
@豆子
公共红{
返回新的红色();
}
@豆子
公共蓝{
返回新的蓝色();
}
@豆子
公共画家(){
返回新的油漆工();
}
}
问题是,;我如何获得画家的颜色列表?另外,还有一点需要注意:我应该让@Configuration返回接口类型还是类


谢谢你的帮助

您所拥有的应该有效,在setter上有
@资源
@自动连线
应该将所有颜色实例注入到您的
列表
字段中

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

@Bean
public List<Color> colorList(){
    List<Color> aList = new ArrayList<>();
    aList.add(blue());
    return aList;
}     
@Bean
公共列表颜色列表(){
列表列表=新的ArrayList();
aList.add(蓝色());
回归主义者;
}     
并将其用作自动连线字段,如下所示:

@Resource(name="colorList") 
public void setColors(List<Color> colors) {
    this.colors = colors;
}
@Resource(name=“colorList”)
公共无效设置颜色(列表颜色){
这个。颜色=颜色;
}

@Resource(name=“colorList”)
私有列表颜色;

关于返回接口或实现的问题,两种方法都可以,但最好使用接口。

嗨,Biju,谢谢你的回答。我还认为它会起作用,但一位同事说,在部署时,Spring抛出了异常。我将对此进行更多的调查。同时,我使用了与你建议的方法相似的方法。太好了!这正是我要找的!有没有办法将列表注入另一个
@Bean
方法?显然,
List
很难按名称插入。建议使用
@Resource
,但这不能作为方法参数。可能与
@Resource(name="colorList")
private List<Color> colors;