如何通过构造函数注入来限定bean

时间:2018-12-14 08:30:30

标签: java spring spring-boot

我有一个在两个地方定义的接口:

@Configuration
public class AppContext {
    @Bean
    public SomeInterface usageOne() {
        return new SameImpl();
    }

    @Bean
    public SomeInterface usageTwo() {
        return new SameImpl(someOtherConfig);
    }

    @Bean
    public Client clientOne(SomeInterface usageOne) {
        return new Client(usageOne);
    }

    @Bean
    public OtherClient clientTwo(SomeInterface usageTwo) {
        return new OtherClient(usageTwo);
    }
}

我的客户端实现类没有仅需要构造函数的任何注释。在这种情况下,如何限定正确的接口实现用法?我不想使用@Primary,因为就我而言,将其中一种用法命名为主要用法在语义上是不正确的(在某种意义上它们是相等的)。我需要使用相同的实现类传递相同的接口,但对于受尊敬的客户端的特定用例,其配置应有所不同。我当时以为将实现注入到bean创建方法中的参数命名就足够了,但是Spring抱怨说:required a single bean, but 2 were found。我不明白如何使用@Qualifier注释。

我正在使用Spring Boot 2.0.4.RELEASE运行,并在单独的配置类中创建了受尊重的bean和客户端,因此创建这样的usageTwo()时我不能只调用OtherClient方法:{{1} },因为此方法在客户端配置类中不可用。

1 个答案:

答案 0 :(得分:2)

正如@chrylis在评论中所提到的,您可以将@Qualifier批注简单地添加到@Bean方法中,如下所示:

@Bean
public Client clientOne(@Qualifier("usageOne") SomeInterface usageOne) {
    return new Client(usageOne);
}

@Bean
public OtherClient clientTwo(@Qualifier("usageTwo") SomeInterface usageTwo) {
    return new OtherClient(usageTwo);
}

指定为@Qualifier批注的值的值是相应bean的名称。这就是相应的@Bean方法的名称,或者是像@Bean("usageThree")这样使用的注释的值。