TogglzApplicationContextBinderApplicationListener implements ApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent && filter.test((ContextRefreshedEvent) event)) { if (ContextClassLoaderApplicationContextHolder.get() != null) { log.warn("ApplicationContext already bound to current context class loader, releasing it first"); ContextClassLoaderApplicationContextHolder.release(); } ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext(); ContextClassLoaderApplicationContextHolder.bind(applicationContext); } else if (event instanceof ContextClosedEvent) { ContextClassLoaderApplicationContextHolder.release(); } } TogglzApplicationContextBinderApplicationListener();  TogglzApplicationContextBinderApplicationListener(ContextRefreshedEventFilter filter); @Override void onApplicationEvent(ApplicationEvent event);  }
@Test void contextRefreshed() { ContextRefreshedEvent contextRefreshedEvent = mock(ContextRefreshedEvent.class); when(contextRefreshedEvent.getApplicationContext()).thenReturn(applicationContext); applicationListener.onApplicationEvent(contextRefreshedEvent); assertSame(applicationContext, ContextClassLoaderApplicationContextHolder.get()); }
@Test void contextRefreshedWhileContextAlreadyBound() { ContextClassLoaderApplicationContextHolder.bind(mock(ApplicationContext.class)); applicationContext = mock(ApplicationContext.class); ContextRefreshedEvent contextRefreshedEvent = mock(ContextRefreshedEvent.class); when(contextRefreshedEvent.getApplicationContext()).thenReturn(applicationContext); applicationListener.onApplicationEvent(contextRefreshedEvent); assertSame(applicationContext, ContextClassLoaderApplicationContextHolder.get()); }
@Test void contextRefreshedIgnored() { ContextClassLoaderApplicationContextHolder.release(); applicationContext = mock(ApplicationContext.class); ContextRefreshedEvent contextRefreshedEvent = mock(ContextRefreshedEvent.class); when(contextRefreshedEvent.getApplicationContext()).thenReturn(applicationContext); ignoringApplicationListener.onApplicationEvent(contextRefreshedEvent); assertSame(null, ContextClassLoaderApplicationContextHolder.get()); }
@Test void contextClosed() { ContextClassLoaderApplicationContextHolder.bind(applicationContext); ContextClosedEvent contextClosedEvent = mock(ContextClosedEvent.class); applicationListener.onApplicationEvent(contextClosedEvent); assertNull(ContextClassLoaderApplicationContextHolder.get()); }