我有一个配置类,它提供同一基本 bean 接口(interface)的两个实现。我希望根据字段上的注释有条件地在 Autowiring 字段上设置这些内容。
public class MyController
{
@Autowired
private MyBeanInterface base;
@Autowired
@MyAnnotation
private MyBeanInterface special;
}
这是配置类的伪代码:
@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 填充带注释的字段?
最佳答案
使用Qualifier注解。示例:
Controller :
在注入(inject)字段添加 Qualifier 注解,并以 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();
}
}
关于java - 如何根据注释为 @Autowire 字段提供不同的 bean 实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48071148/