Eri*_*agt 8 java spring spring-annotations
我有一个Spring bean,在Spring Bean中我依赖于其他bean的列表.我的问题是:如何将bean的通用列表注入该bean的依赖项?
例如,一些代码:
public interface Color { }
public class Red implements Color { }
public class Blue implements Color { }
Run Code Online (Sandbox Code Playgroud)
我的豆子:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是; 如何获取Painter中的颜色列表?另外,在旁注:我应该让@Configuration返回接口类型,还是类?
谢谢您的帮助!
Bij*_*men 15
你有什么应该工作,有一个@Resource或@Autowired在设置器上应该将所有颜色实例注入你的List<Color>领域.
如果您想更明确,可以将集合作为另一个bean返回:
@Bean
public List<Color> colorList(){
List<Color> aList = new ArrayList<>();
aList.add(blue());
return aList;
}
Run Code Online (Sandbox Code Playgroud)
并以这种方式将其用作自动装配的字段:
@Resource(name="colorList")
public void setColors(List<Color> colors) {
this.colors = colors;
}
Run Code Online (Sandbox Code Playgroud)
要么
@Resource(name="colorList")
private List<Color> colors;
Run Code Online (Sandbox Code Playgroud)
关于返回接口或实现的问题,任何一个都应该工作,但接口应该是首选.
| 归档时间: |
|
| 查看次数: |
15831 次 |
| 最近记录: |