From 8a82dd33cb00ae44a02376244d82c24b8ab86a72 Mon Sep 17 00:00:00 2001 From: Gary Russell Date: Tue, 28 Mar 2023 09:54:41 -0400 Subject: [PATCH] GH-2642: Fix Race in KLABeanPostProcessor Resolves https://github.com/spring-projects/spring-kafka/issues/2642 Protect field `ListenerScope` from multi-threaded use (e.g. when creating prototype listeners). **cherry-pick to 2.9.x** --- .../KafkaListenerAnnotationBeanPostProcessor.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/spring-kafka/src/main/java/org/springframework/kafka/annotation/KafkaListenerAnnotationBeanPostProcessor.java b/spring-kafka/src/main/java/org/springframework/kafka/annotation/KafkaListenerAnnotationBeanPostProcessor.java index 97d0411a41..74fdea4c81 100644 --- a/spring-kafka/src/main/java/org/springframework/kafka/annotation/KafkaListenerAnnotationBeanPostProcessor.java +++ b/spring-kafka/src/main/java/org/springframework/kafka/annotation/KafkaListenerAnnotationBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2022 the original author or authors. + * Copyright 2014-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -268,7 +268,7 @@ public void setApplicationContext(ApplicationContext applicationContext) throws * {@link #setEndpointRegistry endpoint registry} has to be explicitly configured. * @param beanFactory the {@link BeanFactory} to be used. */ - public void setBeanFactory(BeanFactory beanFactory) { + public synchronized void setBeanFactory(BeanFactory beanFactory) { this.beanFactory = beanFactory; if (beanFactory instanceof ConfigurableListableBeanFactory clbf) { this.resolver = clbf.getBeanExpressionResolver(); @@ -449,8 +449,8 @@ private KafkaListener enhance(AnnotatedElement element, KafkaListener ann) { } } - private void processMultiMethodListeners(Collection classLevelListeners, List multiMethods, - Object bean, String beanName) { + private synchronized void processMultiMethodListeners(Collection classLevelListeners, + List multiMethods, Object bean, String beanName) { List checkedMethods = new ArrayList<>(); Method defaultMethod = null; @@ -477,7 +477,9 @@ private void processMultiMethodListeners(Collection classLevelLis } } - protected void processKafkaListener(KafkaListener kafkaListener, Method method, Object bean, String beanName) { + protected synchronized void processKafkaListener(KafkaListener kafkaListener, Method method, Object bean, + String beanName) { + Method methodToUse = checkProxy(method, bean); MethodKafkaListenerEndpoint endpoint = new MethodKafkaListenerEndpoint<>(); endpoint.setMethod(methodToUse);