如何根据注释为@Autowire字段提供不同的bean实现?

时间:2018-01-03 04:25:36

标签: java spring spring-boot dependency-injection spring-config

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

public class MyController
{
    @Autowired
    private MyBeanInterface base;

    @Autowired
    @MyAnnotation
    private MyBeanInterface special;
}

这是配置类的pesudo代码:

@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填充带注释的字段?

1 个答案:

答案 0 :(得分:2)

使用Qualifier注释。例如:

<强>控制器:

在注入的字段中添加限定符注释,并将bean id作为参数:

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();
    }
}