Spring 如果 @Configuration 中存在空构造函数,@DynamicPropertySource 将不起作用 class

Spring @DynamicPropertySource does not work if an empty constructor is present in an @Configuration class

我正在使用 TestContainers 进行集成测试,我正在使用 @DynamicPropertySource 来设置 KafkaContainer bootstrap 服务器,如下所示:

@DynamicPropertySource
static void kafkaProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.kafka.bootstrap-servers", () -> { 
        return kafkaContainer1.getHost() + ":" + kafkaContainer1.getFirstMappedPort();
    });
}

这就像一个魅力,即按照我的 KafkaTopicConfiguration class:

@Configuration
public class KafkaTopicConfiguration {

    private String bootstrapServers;

    public KafkaTopicConfiguration(@Value("${spring.kafka.bootstrap-servers}") String bootstrapServers) {
        this.bootstrapServers = bootstrapServers;
    }

其中 bootstrapServers 将获取主机上 Docker 公开的 KafkaContainer 的地址。 现在,我添加了一个空的构造函数,因为我想解决一些问题,就像这样:

public KafkaTopicConfiguration() {
    System.out.println("In KafkaTopicConfiguration constructor");
}

然后 boostrapServers 值突然变成 null。当我删除空构造函数时,它恢复正常。有谁知道为什么?谢谢。

感谢@M.Deinum 指出我的错误。为了后代,我应该在我现有的构造函数上添加 @Autowired 注释,以告诉 Spring 使用哪个构造函数:

@Autowired
public KafkaTopicConfiguration(@Value("${spring.kafka.bootstrap-servers}") String bootstrapServers) {
    this.bootstrapServers = bootstrapServers;
}
    
public KafkaTopicConfiguration() {
    System.out.println("In KafkaTopicConfiguration constructor");
}

我的其他构造函数虽然没有用,但我应该在现有的 1-arg 构造函数上添加 SysOut ;-)