在bean配置方法上使用@Profile注释时,无法注入同一接口的两个字段

时间:2019-02-21 12:26:58

标签: java spring

我使用Spring 5.1.4.RELEASE,并且在bean配置方法上使用@Profile注释时,无法通过构造函数注入同一接口的两个字段。我有一个简单的 Publisher 组件,如下所示:

@Component
public class Publisher {

    private final MyClient prodClient;
    private final MyClient testClient;

    @java.beans.ConstructorProperties({"prodClient", "testClient"})
    public Publisher(MyClient prodClient, MyClient testClient) {
        this.prodClient = prodClient;
        this.testClient = testClient;
    }

}

当我用 @Profile 批注标记整个配置时,它将按预期工作:

@Profile(Profiles.MY_CLIENT)
@Configuration
public class ClientConfig {

    @Bean
    public MyClient prodClient() {
        return new HttpClient("prod.client.channel");
    }

    @Bean
    public MyClient testClient() {
        return new HttpClient("test.client.channel");
    }
}

上面的配置是可以的,但是当我只想在配置类中的某些方法上具有 @Profile 注释时,就会出现问题:

@Configuration
public class ClientConfig {

    @Profile(Profiles.MY_CLIENT)
    @Bean
    public MyClient prodClient() {
        return new HttpClient();
    }

    @Profile(Profiles.MY_CLIENT)
    @Bean
    public MyClient testClient() {
        return new HttpClient();
    }

    // some other beans...
}

然后在启动过程中出现错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.test.Publisher required a bean of type 'com.test.MyClient' that could not be found.

更新: 解决了是我的错我还有另外两个使用不同的@Profile进行注解的bean方法,用于集成测试,但是它们具有相同的生产代码名称(使用 Profiles.MY_CLIENT 配置文件注解):

@Configuration
public class ClientConfig {

    @Profile(Profiles.MY_CLIENT)
    @Bean
    public MyClient prodClient() {
        return new HttpClient();
    }

    @Profile(Profiles.MY_CLIENT)
    @Bean
    public MyClient testClient() {
        return new HttpClient();
    }

    // ... other beans

    @Profile(Profiles.MOCK_MY_CLIENT)
    @Bean
    public MyClient prodClient() {
        return new MockClient();
    }

    @Profile(Profiles.MOCK_MY_CLIENT)
    @Bean
    public MyClient testClient() {
        return new MockClient();
    }
}

2 个答案:

答案 0 :(得分:0)

嗯,如果您尝试注入此组件的列表? 像

public Publisher(List<MyClient> clients) {

}

,并在客户端实现中设置一个标志,该标志可能有助于了解何时应使用它。

答案 1 :(得分:0)

在此代码中:

@java.beans.ConstructorProperties({"prodClient", "testClient"})
public Publisher(MyClient prodClient, MyClient testClient) {
    this.prodClient = prodClient;
    this.testClient = testClient;
}

尝试在参数上使用@Autowired批注:

public Publisher(@Autowired MyClient prodClient, @Autowired MyClient testClient) {
    this.prodClient = prodClient;
    this.testClient = testClient;
}