Skip to content

Commit 04f4db3

Browse files
artembilangaryrussell
authored andcommitted
GH-1059: Add SpEL support for KafkaListener.id()
Fixes #1059 * Code style polishing in the `KafkaListenerAnnotationBeanPostProcessor` and `EnableKafkaIntegrationTests` **Cherry-pick to 2.2.x**
1 parent 95f7c67 commit 04f4db3

File tree

2 files changed

+40
-42
lines changed

2 files changed

+40
-42
lines changed

spring-kafka/src/main/java/org/springframework/kafka/annotation/KafkaListenerAnnotationBeanPostProcessor.java

Lines changed: 19 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -277,14 +277,9 @@ public Object postProcessAfterInitialization(final Object bean, final String bea
277277
final boolean hasClassLevelListeners = classLevelListeners.size() > 0;
278278
final List<Method> multiMethods = new ArrayList<>();
279279
Map<Method, Set<KafkaListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
280-
new MethodIntrospector.MetadataLookup<Set<KafkaListener>>() {
281-
282-
@Override
283-
public Set<KafkaListener> inspect(Method method) {
284-
Set<KafkaListener> listenerMethods = findListenerAnnotations(method);
285-
return (!listenerMethods.isEmpty() ? listenerMethods : null);
286-
}
287-
280+
(MethodIntrospector.MetadataLookup<Set<KafkaListener>>) method -> {
281+
Set<KafkaListener> listenerMethods = findListenerAnnotations(method);
282+
return (!listenerMethods.isEmpty() ? listenerMethods : null);
288283
});
289284
if (hasClassLevelListeners) {
290285
Set<Method> methodsWithHandler = MethodIntrospector.selectMethods(targetClass,
@@ -427,8 +422,7 @@ protected void processListener(MethodKafkaListenerEndpoint<?, ?> endpoint, Kafka
427422
endpoint.setTopicPartitions(resolveTopicPartitions(kafkaListener));
428423
endpoint.setTopics(resolveTopics(kafkaListener));
429424
endpoint.setTopicPattern(resolvePattern(kafkaListener));
430-
endpoint.setClientIdPrefix(resolveExpressionAsString(kafkaListener.clientIdPrefix(),
431-
"clientIdPrefix"));
425+
endpoint.setClientIdPrefix(resolveExpressionAsString(kafkaListener.clientIdPrefix(), "clientIdPrefix"));
432426
String group = kafkaListener.containerGroup();
433427
if (StringUtils.hasText(group)) {
434428
Object resolvedGroup = resolveExpression(group);
@@ -475,11 +469,14 @@ private void resolveKafkaProperties(MethodKafkaListenerEndpoint<?, ?> endpoint,
475469
if (propertyStrings.length > 0) {
476470
Properties properties = new Properties();
477471
for (String property : propertyStrings) {
478-
try {
479-
properties.load(new StringReader(resolveExpressionAsString(property, "property")));
480-
}
481-
catch (IOException e) {
482-
this.logger.error("Failed to load property " + property + ", continuing...", e);
472+
String value = resolveExpressionAsString(property, "property");
473+
if (value != null) {
474+
try {
475+
properties.load(new StringReader(value));
476+
}
477+
catch (IOException e) {
478+
this.logger.error("Failed to load property " + property + ", continuing...", e);
479+
}
483480
}
484481
}
485482
endpoint.setConsumerProperties(properties);
@@ -488,7 +485,7 @@ private void resolveKafkaProperties(MethodKafkaListenerEndpoint<?, ?> endpoint,
488485

489486
private String getEndpointId(KafkaListener kafkaListener) {
490487
if (StringUtils.hasText(kafkaListener.id())) {
491-
return resolve(kafkaListener.id());
488+
return resolveExpressionAsString(kafkaListener.id(), "id");
492489
}
493490
else {
494491
return GENERATED_ID_PREFIX + this.counter.getAndIncrement();
@@ -514,19 +511,19 @@ private TopicPartitionInitialOffset[] resolveTopicPartitions(KafkaListener kafka
514511
result.addAll(resolveTopicPartitionsList(topicPartition));
515512
}
516513
}
517-
return result.toArray(new TopicPartitionInitialOffset[result.size()]);
514+
return result.toArray(new TopicPartitionInitialOffset[0]);
518515
}
519516

520517
private String[] resolveTopics(KafkaListener kafkaListener) {
521518
String[] topics = kafkaListener.topics();
522519
List<String> result = new ArrayList<>();
523520
if (topics.length > 0) {
524-
for (int i = 0; i < topics.length; i++) {
525-
Object topic = resolveExpression(topics[i]);
521+
for (String topic1 : topics) {
522+
Object topic = resolveExpression(topic1);
526523
resolveAsString(topic, result);
527524
}
528525
}
529-
return result.toArray(new String[result.size()]);
526+
return result.toArray(new String[0]);
530527
}
531528

532529
private Pattern resolvePattern(KafkaListener kafkaListener) {
@@ -558,8 +555,8 @@ private List<TopicPartitionInitialOffset> resolveTopicPartitionsList(TopicPartit
558555
Assert.state(partitions.length > 0 || partitionOffsets.length > 0,
559556
"At least one 'partition' or 'partitionOffset' required in @TopicPartition for topic '" + topic + "'");
560557
List<TopicPartitionInitialOffset> result = new ArrayList<>();
561-
for (int i = 0; i < partitions.length; i++) {
562-
resolvePartitionAsInteger((String) topic, resolveExpression(partitions[i]), result);
558+
for (String partition : partitions) {
559+
resolvePartitionAsInteger((String) topic, resolveExpression(partition), result);
563560
}
564561

565562
for (PartitionOffset partitionOffset : partitionOffsets) {

spring-kafka/src/test/java/org/springframework/kafka/annotation/EnableKafkaIntegrationTests.java

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
package org.springframework.kafka.annotation;
1818

1919
import static org.assertj.core.api.Assertions.assertThat;
20-
import static org.assertj.core.api.Assertions.assertThatThrownBy;
20+
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
2121
import static org.mockito.ArgumentMatchers.anyMap;
2222
import static org.mockito.ArgumentMatchers.anyString;
2323
import static org.mockito.ArgumentMatchers.isNull;
@@ -255,7 +255,7 @@ public void testSimple() throws Exception {
255255
"listenerConsumer.consumer"));
256256
assertThat(
257257
KafkaTestUtils.getPropertyValue(this.listener.listen4Consumer, "fetcher.maxPollRecords", Integer.class))
258-
.isEqualTo(100);
258+
.isEqualTo(100);
259259
assertThat(this.quxGroup).hasSize(1);
260260
assertThat(this.quxGroup.get(0)).isSameAs(manualContainer);
261261
List<?> containers = KafkaTestUtils.getPropertyValue(manualContainer, "containers", List.class);
@@ -309,14 +309,12 @@ public void testSimple() throws Exception {
309309
.isNotEqualTo("rebalanceListener");
310310
String clientId = KafkaTestUtils.getPropertyValue(rebalanceContainer, "listenerConsumer.consumer.clientId",
311311
String.class);
312-
assertThat(
313-
clientId)
314-
.startsWith("rebal-");
312+
assertThat(clientId).startsWith("rebal-");
315313
assertThat(clientId.indexOf('-')).isEqualTo(clientId.lastIndexOf('-'));
316314
}
317315

318316
@Test
319-
public void testAutoStartup() throws Exception {
317+
public void testAutoStartup() {
320318
MessageListenerContainer listenerContainer = registry.getListenerContainer("manualStart");
321319
assertThat(listenerContainer).isNotNull();
322320
assertThat(listenerContainer.isRunning()).isFalse();
@@ -399,7 +397,6 @@ public void testJson() throws Exception {
399397
}
400398

401399
@Test
402-
@DirtiesContext
403400
public void testJsonHeaders() throws Exception {
404401
ConcurrentMessageListenerContainer<?, ?> container =
405402
(ConcurrentMessageListenerContainer<?, ?>) registry.getListenerContainer("jsonHeaders");
@@ -546,7 +543,7 @@ public void testValidation() throws Exception {
546543
}
547544

548545
@Test
549-
public void testReplyingListener() throws Exception {
546+
public void testReplyingListener() {
550547
Map<String, Object> consumerProps = new HashMap<>(this.consumerFactory.getConfigurationProperties());
551548
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "testReplying");
552549
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
@@ -560,7 +557,7 @@ public void testReplyingListener() throws Exception {
560557
}
561558

562559
@Test
563-
public void testReplyingBatchListener() throws Exception {
560+
public void testReplyingBatchListener() {
564561
Map<String, Object> consumerProps = new HashMap<>(this.consumerFactory.getConfigurationProperties());
565562
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "testBatchReplying");
566563
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
@@ -586,7 +583,7 @@ public void testReplyingBatchListener() throws Exception {
586583
}
587584

588585
@Test
589-
public void testReplyingListenerWithErrorHandler() throws Exception {
586+
public void testReplyingListenerWithErrorHandler() {
590587
Map<String, Object> consumerProps = new HashMap<>(this.consumerFactory.getConfigurationProperties());
591588
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "testErrorHandlerReplying");
592589
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
@@ -600,7 +597,7 @@ public void testReplyingListenerWithErrorHandler() throws Exception {
600597
}
601598

602599
@Test
603-
public void testVoidListenerWithReplyingErrorHandler() throws Exception {
600+
public void testVoidListenerWithReplyingErrorHandler() {
604601
Map<String, Object> consumerProps = new HashMap<>(this.consumerFactory.getConfigurationProperties());
605602
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "testVoidWithErrorHandlerReplying");
606603
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
@@ -614,7 +611,7 @@ public void testVoidListenerWithReplyingErrorHandler() throws Exception {
614611
}
615612

616613
@Test
617-
public void testReplyingBatchListenerWithErrorHandler() throws Exception {
614+
public void testReplyingBatchListenerWithErrorHandler() {
618615
Map<String, Object> consumerProps = new HashMap<>(this.consumerFactory.getConfigurationProperties());
619616
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "testErrorHandlerBatchReplying");
620617
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
@@ -640,7 +637,7 @@ public void testReplyingBatchListenerWithErrorHandler() throws Exception {
640637
}
641638

642639
@Test
643-
public void testMultiReplyTo() throws Exception {
640+
public void testMultiReplyTo() {
644641
Map<String, Object> consumerProps = new HashMap<>(this.consumerFactory.getConfigurationProperties());
645642
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "testMultiReplying");
646643
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
@@ -709,10 +706,12 @@ public void testAddingTopics() {
709706
assertThat(embeddedKafka.getTopics().size()).isEqualTo(count + 1);
710707
embeddedKafka.addTopics(new NewTopic("morePartitions", 10, (short) 1));
711708
assertThat(embeddedKafka.getTopics().size()).isEqualTo(count + 2);
712-
assertThatThrownBy(() -> embeddedKafka.addTopics(new NewTopic("morePartitions", 10, (short) 1)))
713-
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("exists");
714-
assertThatThrownBy(() -> embeddedKafka.addTopics(new NewTopic("morePartitions2", 10, (short) 2)))
715-
.isInstanceOf(IllegalArgumentException.class).hasMessageContaining("replication");
709+
assertThatIllegalArgumentException()
710+
.isThrownBy(() -> embeddedKafka.addTopics(new NewTopic("morePartitions", 10, (short) 1)))
711+
.withMessageContaining("exists");
712+
assertThatIllegalArgumentException()
713+
.isThrownBy(() -> embeddedKafka.addTopics(new NewTopic("morePartitions2", 10, (short) 2)))
714+
.withMessageContaining("replication");
716715
Map<String, Object> consumerProps = new HashMap<>(this.consumerFactory.getConfigurationProperties());
717716
consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "testMultiReplying");
718717
ConsumerFactory<Integer, String> cf = new DefaultKafkaConsumerFactory<>(consumerProps);
@@ -733,7 +732,7 @@ public void testReceivePollResults() throws Exception {
733732
@Test
734733
public void testAutoConfigTm() {
735734
assertThat(this.transactionalFactory.getContainerProperties().getTransactionManager())
736-
.isInstanceOf(ChainedKafkaTransactionManager.class);
735+
.isInstanceOf(ChainedKafkaTransactionManager.class);
737736
}
738737

739738
@Test
@@ -1416,8 +1415,9 @@ public void listen3(ConsumerRecord<?, ?> record) {
14161415
this.latch3.countDown();
14171416
}
14181417

1419-
@KafkaListener(id = "qux", topics = "annotated4", containerFactory = "kafkaManualAckListenerContainerFactory",
1420-
containerGroup = "qux#{'Group'}", properties = {
1418+
@KafkaListener(id = "#{'qux'}", topics = "annotated4",
1419+
containerFactory = "kafkaManualAckListenerContainerFactory", containerGroup = "qux#{'Group'}",
1420+
properties = {
14211421
"max.poll.interval.ms:#{'${poll.interval:60000}'}",
14221422
ConsumerConfig.MAX_POLL_RECORDS_CONFIG + "=#{'${poll.recs:100}'}"
14231423
})
@@ -1879,6 +1879,7 @@ public void setDelegate(
18791879
public Foo convert(String source) {
18801880
return delegate.convert(source);
18811881
}
1882+
18821883
}
18831884

18841885
public static class ValidatedClass {

0 commit comments

Comments
 (0)