GH-2451: Fix Class Level Listener Multi Instances

Resolves https://github.com/spring-projects/spring-kafka/issues/2451

Classes with class level `@KafkaListener` were incorrectly added
to the `nonAnnotatedClasses` set, preventing multiple instances
of the same class to be registered as listeners.

**cherry-pick to 2.9.x, 2.8.x**

* Fix CheckStyle.
This commit is contained in:
Gary Russell
2022-10-21 16:49:11 -04:00
committed by Artem Bilan
parent a77125f12e
commit 48b2017b0d
2 changed files with 37 additions and 2 deletions

View File

@@ -362,7 +362,7 @@ public class KafkaListenerAnnotationBeanPostProcessor<K, V>
AnnotationUtils.findAnnotation(method, KafkaHandler.class) != null);
multiMethods.addAll(methodsWithHandler);
}
if (annotatedMethods.isEmpty()) {
if (annotatedMethods.isEmpty() && !hasClassLevelListeners) {
this.nonAnnotatedClasses.add(bean.getClass());
this.logger.trace(() -> "No @KafkaListener annotations found on bean type: " + bean.getClass());
}

View File

@@ -185,7 +185,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
"annotated29", "annotated30", "annotated30reply", "annotated31", "annotated32", "annotated33",
"annotated34", "annotated35", "annotated36", "annotated37", "foo", "manualStart", "seekOnIdle",
"annotated38", "annotated38reply", "annotated39", "annotated40", "annotated41", "annotated42",
"annotated43", "annotated43reply"})
"annotated43", "annotated43reply" })
@TestPropertySource(properties = "spel.props=fetch.min.bytes=420000,max.poll.records=10")
public class EnableKafkaIntegrationTests {
@@ -1009,6 +1009,12 @@ public class EnableKafkaIntegrationTests {
this.registry.setAlwaysStartAfterRefresh(true);
}
@Test
void classLevelTwoInstancesSameClass() {
assertThat(this.registry.getListenerContainer("multiTwoOne")).isNotNull();
assertThat(this.registry.getListenerContainer("multiTwoTwo")).isNotNull();
}
@Configuration
@EnableKafka
@EnableTransactionManagement(proxyTargetClass = true)
@@ -1731,6 +1737,16 @@ public class EnableKafkaIntegrationTests {
return new ProtoListener();
}
@Bean
MultiListenerTwoInstances multiInstanceOne() {
return new MultiListenerTwoInstances("multiTwoOne");
}
@Bean
MultiListenerTwoInstances multiInstanceTwo() {
return new MultiListenerTwoInstances("multiTwoTwo");
}
}
static class ProtoListener {
@@ -2461,6 +2477,25 @@ public class EnableKafkaIntegrationTests {
}
@KafkaListener(id = "#{__listener.id}", topics = "multiWithTwoInstances", autoStartup = "false")
static class MultiListenerTwoInstances {
private final String id;
MultiListenerTwoInstances(String id) {
this.id = id;
}
public String getId() {
return this.id;
}
@KafkaHandler
void listen(String in) {
}
}
public interface Bar {
String getBar();