![](/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.