首页 > 解决方案 > Spring Boot 找不到 EmbeddedKafkaBroker Bean

问题描述

我正在为 Kafka 编写集成测试。为此,我正在使用 Spring 的EmbeddedKafka. 这是我的课:

@Component
@EmbeddedKafka(
    partitions = 1,
    topics = {"Topic},
    brokerProperties = {"listeners=PLAINTEXT://localhost:9091", "port=9091"})
public class KafkaConsumerTestUtils {
  @Autowired private EmbeddedKafkaBroker embeddedKafka;
  ....
}

我在我的类中自动装配这个 utils 类,用@SpringBootTest. 这是我得到的错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.kafka.test.EmbeddedKafkaBroker' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1646)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1205)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1166)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 66 more

奇怪的是,当我在我EmbeddedKafkaBroker的任何测试类中自动装配时,它被创建并且测试运行良好。

有人可以帮我弄这个吗?

标签: javaspringspring-bootapache-kafka

解决方案


不完全确定为什么,但看起来您没有按照预期的方式使用它。

@EmbeddedKafka 是一个注释,可以在运行基于 Spring Kafka 的测试的测试类上指定。

文档指出:

The typical usage of this annotation is like:
 @RunWith(SpringRunner.class)
 @EmbeddedKafka
 public class MyKafkaTests {}

推荐阅读