如何根据注释为@Autowire 字段提供不同的bean 实现?
How provide a different bean implementation to @Autowire field based on annotation?
我有一个配置 class,它提供了相同基 bean 接口的两个实现。我希望根据字段上的注释有条件地在自动装配字段上设置这些。
public class MyController
{
@Autowired
private MyBeanInterface base;
@Autowired
@MyAnnotation
private MyBeanInterface special;
}
这是配置的伪代码 class:
@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注释。示例:
控制器:
在以 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();
}
}
我有一个配置 class,它提供了相同基 bean 接口的两个实现。我希望根据字段上的注释有条件地在自动装配字段上设置这些。
public class MyController
{
@Autowired
private MyBeanInterface base;
@Autowired
@MyAnnotation
private MyBeanInterface special;
}
这是配置的伪代码 class:
@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注释。示例:
控制器:
在以 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();
}
}