Skip to content

Avoid duplicate ApplicationListener firing (proxy vs. target) #28322

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,24 @@ private Collection<ApplicationListener<?>> retrieveApplicationListeners(
if (supportsEvent(beanFactory, listenerBeanName, eventType)) {
ApplicationListener<?> listener =
beanFactory.getBean(listenerBeanName, ApplicationListener.class);

// Despite best efforts to avoid it, unwrapped proxies (singleton targets) can end up in the
// list of programmatically registered listeners. In order to avoid duplicates, we need to find
// and replace them by their proxy counterparts, because if both a proxy and its target end up
// in 'allListeners', listeners will fire twice.
ApplicationListener<?> unwrappedListener =
(ApplicationListener<?>) AopProxyUtils.getSingletonTarget(listener);
if (listener != unwrappedListener) {
if (filteredListeners != null && filteredListeners.contains(unwrappedListener)) {
filteredListeners.remove(unwrappedListener);
filteredListeners.add(listener);
}
if (allListeners.contains(unwrappedListener)) {
allListeners.remove(unwrappedListener);
allListeners.add(listener);
}
}

if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {
if (retriever != null) {
if (beanFactory.isSingleton(listenerBeanName)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.test.self_inject.MyApplication;
import org.springframework.context.event.test.self_inject.MyEventListener;
import org.springframework.context.event.test.self_inject.MyEventPublisher;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.context.support.StaticMessageSource;
Expand Down Expand Up @@ -244,6 +249,24 @@ public void proxiedListenersMixedWithTargetListeners() {
assertThat(listener1.seenEvents).hasSize(2);
}

/**
* Regression test for <a href="https://github.com/spring-projects/spring-framework/issues/28283">issue 28283</a>,
* where event listeners proxied due to e.g.
* <ul>
* <li>{@code @Transactional} annotations in their methods or</li>
* <li>being targeted by aspects</li>
* </ul>
* were added to the list of application listener beans twice (both proxy and unwrapped target).
*/
@Test
public void eventForSelfInjectedProxiedListenerFiredOnlyOnce() {
String basePackage = MyApplication.class.getPackageName();
AbstractApplicationContext context = new AnnotationConfigApplicationContext(basePackage);
context.getBean(MyEventPublisher.class).publishMyEvent("hello");
assertThat(MyEventListener.eventCount).isEqualTo(1);
context.close();
}

@Test
public void testEventPublicationInterceptor() throws Throwable {
MethodInvocation invocation = mock();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package org.springframework.context.event.test.self_inject;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.support.AbstractApplicationContext;

@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MyApplication {
public static void main(String[] args) {
try (AbstractApplicationContext context = new AnnotationConfigApplicationContext("org.springframework.context.event.test.self_inject")) {
context.getBean(MyEventPublisher.class).publishMyEvent("hello");
assert MyEventListener.eventCount == 1 : "event listener must fire exactly once";
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.springframework.context.event.test.self_inject;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class MyAspect {
@Before("within(org.springframework.context.event.test.self_inject.MyEventListener)")
public void myAdvice(JoinPoint joinPoint) {
//System.out.println(joinPoint);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package org.springframework.context.event.test.self_inject;

import org.springframework.context.ApplicationEvent;

public class MyEvent extends ApplicationEvent {
private String message;

public MyEvent(Object source, String message) {
super(source);
this.message = message;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package org.springframework.context.event.test.self_inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class MyEventListener implements ApplicationListener<MyEvent> {
public static int eventCount;

@Autowired // use '-Dspring.main.allow-circular-references=true' in Spring Boot >= 2.6.0
//@Lazy // with '@Lazy', the problem does not occur
private MyEventListener eventDemoListener;

@Override
public void onApplicationEvent(MyEvent event) {
//System.out.println("Event: " + event);
eventCount++;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package org.springframework.context.event.test.self_inject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

@Component
public class MyEventPublisher {
@Autowired
private ApplicationEventPublisher eventPublisher;

public void publishMyEvent(String message) {
eventPublisher.publishEvent(new MyEvent(this, message));
}
}