@Test public void lambdaAsListenerWithErrorHandler() { final Set<MyEvent> seenEvents = new HashSet<>(); StaticApplicationContext context = new StaticApplicationContext(); SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(); multicaster.setErrorHandler(ReflectionUtils::rethrowRuntimeException); context.getBeanFactory().registerSingleton( StaticApplicationContext.APPLICATION_EVENT_MULTICASTER_BEAN_NAME, multicaster); ApplicationListener<MyEvent> listener = seenEvents::add; context.addApplicationListener(listener); context.refresh(); MyEvent event1 = new MyEvent(context); context.publishEvent(event1); context.publishEvent(new MyOtherEvent(context)); MyEvent event2 = new MyEvent(context); context.publishEvent(event2); assertSame(2, seenEvents.size()); assertTrue(seenEvents.contains(event1)); assertTrue(seenEvents.contains(event2)); context.close(); }
@Test public void simpleApplicationEventMulticasterWithErrorHandler() { @SuppressWarnings("unchecked") ApplicationListener<ApplicationEvent> listener = mock(ApplicationListener.class); ApplicationEvent evt = new ContextClosedEvent(new StaticApplicationContext()); SimpleApplicationEventMulticaster smc = new SimpleApplicationEventMulticaster(); smc.setErrorHandler(TaskUtils.LOG_AND_SUPPRESS_ERROR_HANDLER); smc.addApplicationListener(listener); willThrow(new RuntimeException()).given(listener).onApplicationEvent(evt); smc.multicastEvent(evt); }
@Override public void failed(ConfigurableApplicationContext context, Throwable exception) { ApplicationFailedEvent event = new ApplicationFailedEvent(this.application, this.args, context, exception); if (context != null && context.isActive()) { // Listeners have been registered to the application context so we should // use it at this point if we can context.publishEvent(event); } else { // An inactive context may not have a multicaster so we use our multicaster to // call all of the context's listeners instead if (context instanceof AbstractApplicationContext) { for (ApplicationListener<?> listener : ((AbstractApplicationContext) context) .getApplicationListeners()) { this.initialMulticaster.addApplicationListener(listener); } } this.initialMulticaster.setErrorHandler(new LoggingErrorHandler()); this.initialMulticaster.multicastEvent(event); } }