我有一个配置类,它提供了同一基础 Bean 接口的两个实现。我希望根据字段上的注释有条件地在自动连线字段上设置这些。
public class MyController
{
@Autowired
private MyBeanInterface base;
@Autowired
@MyAnnotation
private MyBeanInterface special;
}
这是配置类的 pesudo-code:
@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 作为参数:
public class MyController
{
@Autowired
@Qualifier("normalBean")
private MyBeanInterface base;
@Autowired
@Qualifier("specialBean")
private MyBeanInterface special;
}
配置类
指定 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();
}
}