spring @DynamicPropertySource不会覆盖KafkaProperties

mctunoxg  于 4个月前  发布在  Spring
关注(0)|答案(2)|浏览(58)

我在TestContainer中使用Kafka,@DynamicPropertySource不会覆盖我在应用程序代码(src/main)中使用的KafkaProperties。甚至在KafkaContainer之前,KafkaProperties也会在上下文中加载。下面你可以看到我的配置。
生产代码中的KafkaProducerConfigmain)。

@Bean
public <T> KafkaProducer<String, T> defaultKafkaProducer(KafkaProperties kafkaProperties) {
    Map<String, Object> props = new HashMap<>();

    props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers());
    ...
}

字符串
在测试中,我使用@Config对容器配置进行了抽象集成测试。

@Log4j2
@AutoConfigureMetrics
@TestPropertySource(locations = "classpath:application-test.properties")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {Application.class})
@AutoConfigureWireMock(port = 0)
//@Testcontainers
@Import(KafkaTestContainerConfig.class)
public abstract class AbstractIntegrationTest {
    ...
}
@Configuration
public class KafkaTestContainerConfig {

    @Container
    public static KafkaContainer kafka = new KafkaContainer(
        DockerImageName.parse("confluentinc/cp-kafka:7.2.2.arm64"))
        .withEnv("KAFKA_AUTO_CREATE_TOPICS_ENABLE", "true")
        .withEnv("KAFKA_CREATE_TOPICS", "my-topic")
        .withEmbeddedZookeeper();

    @DynamicPropertySource
    public static void addKafkaProperties(DynamicPropertyRegistry registry) {
        kafka.start();

        registry.add("spring.kafka.bootstrap-servers", () -> "localhost:" + kafka.getMappedPort(9093).toString());
}

的数据
当我运行/调试测试时,生产者配置的kafkaProperties.getBootstrapServers()获得默认的引导值。请注意,我看到defaultKafkaProducer在Kafka容器之前执行。我试图将@TestContainer添加到AbstractIntegrationTests(正如你在上面看到的),但它没有效果,这是有意义的,因为我知道容器生命周期集成在Spring测试生命周期的托管中。我试图将@Autowired添加到DynamicPropertyRegistryKafkaProperties中,没有任何影响(这也是意料之中的)。我还试图避免KafkaTestContainerConfig类将容器配置移动到抽象集成测试类,但同样的结果是我觉得我误解了生命周期管理的一些东西,但我找不到错误。
我正在使用SpringBoot 2.7.X与Spring 5.3.X和JDK 17。

yrwegjxp

yrwegjxp1#

我也遇到了同样的问题,可以通过避免KafkaAdmin自动配置,而是手动创建并覆盖bootstrapServer来解决它。不确定这是否是最好的方法,但至少它对我运行绿色测试有效。

@Bean
public KafkaAdmin kafkaAdmin(KafkaConnectionDetails connectionDetails) {
    connectionDetails.getBootstrapServers().clear();
    connectionDetails.getBootstrapServers().add(this.bootstrapServerUrl);
    return new KafkaAdmin(producerConfig());
}

字符串

gzjq41n4

gzjq41n42#

最后,我修复了将@DynamicPropertySource和容器开始移动到AbstractIntegrationTest类的问题,似乎注解必须与SpringBootTest在同一个类中,以确保它以预期的顺序执行

相关问题