![](/img/trans.png)
[英]How to inject Beans inside a test class properly with spring boot and annotations
[英]How to inject custom list of beans in spring boot
假设所有BarX
都是Foo
类型的孩子。
我的 bean 配置 class 是:
class MyConfig{
@Bean
public Foo barA() {
return new BarA();
}
@Bean
public Foo barB() {
return new BarB();
}
@Bean
public Foo barC() {
return new BarC();
}
@Bean
public List<Foo> getDefaultFoos(BarA barA, BarB barB) {
return List.of(barA, barB);
}
@Bean
public OtherType other(List<Foo> defaultFoos, ApplicationContext applicationContext) {
return new OtherType(defaultFoos, applicationContext);
/* Expecting `List<Foo> defaultFoos` from method `getDefaultFoos` which is [barA, barB]
but getting list of all Bars which is [barA, barB, barC]
*/
}
}
在方法OtherType other
中,
期望来自方法getDefaultFoos
的List<Foo> defaultFoos
仅为[barA, barB]
但获取所有 Bars 的列表[barA, barB, barC]
如何在“其他”bean中注入自定义列表Foo而不是全部?
使用@Qualifier指定您需要的确切 bean。
@Bean
public OtherType other(@Qualifier("getDefaultFoos") List<Foo> defaultFoos, ApplicationContext applicationContext) {
return new OtherType(defaultFoos, applicationContext);
}
当您自动装配某些内容的列表时,默认行为是获取每个 bean 匹配,您在此处看到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.