![](/img/trans.png)
[英]How provide a different bean to an @Autowire field conditional on an annotation on the owning object which is also @Autowired?
[英]How provide a different bean implementation to @Autowire field based on annotation?
我有一個配置類,提供了相同基本bean接口的兩個實現。 我希望根據字段上的注釋有條件地在自動裝配的字段上設置這些內容。
public class MyController
{
@Autowired
private MyBeanInterface base;
@Autowired
@MyAnnotation
private MyBeanInterface special;
}
這是config類的偽代碼:
@Configuration
public class ConfigClass
{
@Bean
@Primary
public MyBeanInterface getNormalBeanInterface()
{
return new MyBeanInterfaceImpl();
}
@Bean
//This doesn't work
@ConditionalOnClass(MyAnnotation.class)
public MyBeanInterface getSpecialBeanInterface()
{
return new MyBeanInterfaceForMyAnnotation();
}
}
如何使第二個bean填充帶注釋的字段?
使用限定符注釋。 例:
控制器:
在注入的字段(帶有bean id作為參數)上添加Qualifier批注:
public class MyController
{
@Autowired
@Qualifier("normalBean")
private MyBeanInterface base;
@Autowired
@Qualifier("specialBean")
private MyBeanInterface special;
}
ConfigClass
指定bean ID:
@Configuration
public class ConfigClass
{
@Bean(name="normalBean")
@Primary
public MyBeanInterface getNormalBeanInterface()
{
return new MyBeanInterfaceImpl();
}
@Bean(name="specialBean")
public MyBeanInterface getSpecialBeanInterface()
{
return new MyBeanInterfaceForMyAnnotation();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.