0

我有一个配置类,它提供了相同基 bean 接口的两个实现。我希望根据字段上的注释有条件地在自动装配字段上设置这些。

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 填充?

4

1 回答 1

2

使用限定符注释。例子:

控制器:

在以 bean id 作为参数的注入字段中添加 Qualifier 注释:

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();
    }
}
于 2018-01-03T04:47:55.103 回答