我有一个 Spring Boot 应用程序,它有一个消费者从一个集群中的主题消费并产生到不同集群中的另一个主题。现在我正在尝试使用 spring 嵌入式 Kafka 编写集成测试用例,但遇到了问题KafkaTemplate could not be registered. A bean with that name has already been defined in class path resource消费类@Servicepublic class KafkaConsumerService {@Autowiredprivate KafkaProducerService kafkaProducerService;@KafkaListener(topics = "${kafka.producer.topic}")public void professor(List<Professor> pro) { pro.forEach(kafkaProducerService::produce); }}生产者类@Servicepublic class KafkaProducerService {@Value("${kafka.producer.topic}")private String topic;@Autowiredprivate KafkaTemplate<String, Object> kafkaTemplate;public void produce(Professor pro) { kafkaTemplate.send(topic,"professor",pro); } }在我的测试用例中,我想覆盖KafkaTemplate,这样当我调用其中的kafkaConsumerService.professor方法时,Test它应该将数据生成到嵌入式 Kafka 中,并且我应该对其进行验证。测试配置@TestConfiguration@EmbeddedKafka(partitions = 1, controlledShutdown = false,brokerProperties = {"listeners=PLAINTEXT://localhost:3333", "port=3333"})public class KafkaProducerConfigTest {@Autowired KafkaEmbedded kafkaEmbeded;@AutowiredKafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;@Beforepublic void setUp() throws Exception { for (MessageListenerContainer messageListenerContainer : kafkaListenerEndpointRegistry.getListenerContainers()) { ContainerTestUtils.waitForAssignment(messageListenerContainer, kafkaEmbeded.getPartitionsPerTopic()); }}@Beanpublic ProducerFactory<String, Object> producerFactory() { return new DefaultKafkaProducerFactory<>(KafkaTestUtils.producerProps(kafkaEmbeded));}@Beanpublic KafkaTemplate<String, Object> kafkaTemplate() { KafkaTemplate<String, Object> kafkaTemplate = new KafkaTemplate<>(producerFactory()); return kafkaTemplate; } }
1 回答
月关宝盒
TA贡献1772条经验 获得超5个赞
Boot 2.1默认禁用 bean 覆盖。
默认情况下禁用 Bean 覆盖,以防止意外覆盖 bean。如果您依赖于覆盖,则需要设置
spring.main.allow-bean-definition-overriding
为true
.
关于弃用;请参阅 .java 文档@EmbeddedKafka
。它被替换为EmbeddedKafkaBroker
。
添加回答
举报
0/150
提交
取消