Skip to content

Commit

Permalink
ApplicationListenerMethodAdapter: gracefully handle beans which are a…
Browse files Browse the repository at this point in the history
…ctually NullBean

Currently, if you have an optional event listener (via a @bean method returning `null`)
this causes the event multicaster to explode violently.  Now, we just safely skip it.
  • Loading branch information
stevenschlansker authored and jhoeller committed Nov 11, 2019
1 parent d494621 commit fc55e66
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,9 @@ private boolean shouldHandle(ApplicationEvent event, @Nullable Object[] args) {
@Nullable
protected Object doInvoke(Object... args) {
Object bean = getTargetBean();
if (bean.equals(null)) {
return null;
}
ReflectionUtils.makeAccessible(this.method);
try {
return this.method.invoke(bean, args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package org.springframework.context.event;

import java.io.Closeable;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
Expand All @@ -24,12 +26,14 @@
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Disabled;
Expand Down Expand Up @@ -622,6 +626,12 @@ public void listenersReceiveEarlyEvents() {
assertThat(listener.order).contains("first", "second", "third");
}

@Test
public void missingBeanDoesntCrash() {
load(MissingEventListener.class);
context.getBean(UseMissingEventListener.class);
context.getBean(ApplicationEventMulticaster.class).multicastEvent(new TestEvent(this));
}

private void load(Class<?>... classes) {
List<Class<?>> allClasses = new ArrayList<>();
Expand Down Expand Up @@ -1076,4 +1086,32 @@ public String getConversationId() {
}
}

@Configuration
@Import({UseMissingEventListener.class})
public static class MissingEventListener {
@Bean
public MyEventListener missing() {
return null;
}
}

@Component
public static class MyEventListener implements Closeable {
@EventListener
public void hear(TestEvent e) {
throw new AssertionError();
}

@Override
public void close() throws IOException {}
}

public static class UseMissingEventListener {
@Inject
public UseMissingEventListener(Optional<MyEventListener> notHere) {
if (notHere.isPresent()) {
throw new AssertionError();
}
}
}
}

0 comments on commit fc55e66

Please sign in to comment.