org.springframework.context.event.ContextClosedEvent Java Examples
The following examples show how to use
org.springframework.context.event.ContextClosedEvent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApplicationEventListener.java From SpringBoot-Base-System with GNU Lesser General Public License v3.0 | 6 votes |
/** * 应用程序启动过程监听 * * @time 2018年4月10日 下午5:05:33 * @version V1.0 * @param event */ @Override public void onApplicationEvent(ApplicationEvent event) { // 在这里可以监听到Spring Boot的生命周期 if (event instanceof ApplicationEnvironmentPreparedEvent) { // 初始化环境变量 log.debug("初始化环境变量"); } else if (event instanceof ApplicationPreparedEvent) { // 初始化完成 log.debug("初始化环境变量完成"); } else if (event instanceof ContextRefreshedEvent) { // 应用刷新,当ApplicationContext初始化或者刷新时触发该事件。 log.debug("应用刷新"); } else if (event instanceof ApplicationReadyEvent) {// 应用已启动完成 log.debug("应用已启动完成"); } else if (event instanceof ContextStartedEvent) { // 应用启动,Spring2.5新增的事件,当容器调用ConfigurableApplicationContext的 // Start()方法开始/重新开始容器时触发该事件。 log.debug("应用启动"); } else if (event instanceof ContextStoppedEvent) { // 应用停止,Spring2.5新增的事件,当容器调用ConfigurableApplicationContext // 的Stop()方法停止容器时触发该事件。 log.debug("应用停止"); } else if (event instanceof ContextClosedEvent) { // 应用关闭,当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有 // 单例Bean都被销毁。 log.debug("应用关闭"); } else { } }
Example #2
Source File: WorkerManagerTest.java From score with Apache License 2.0 | 6 votes |
@Test public void startUpWithFailure() throws Exception { //shutting the service down workerManager.onApplicationEvent(mock(ContextClosedEvent.class)); assertThat(workerManager.isUp()).isFalse(); reset(workerNodeService); doThrow(new RuntimeException("try 1")) .doThrow(new RuntimeException("try 2")) .doThrow(new RuntimeException("try 3")) .doReturn("1") .when(workerNodeService).up(CREDENTIAL_UUID, "version", "123"); //start again workerManager.onApplicationEvent(mock(ContextRefreshedEvent.class)); Thread.sleep(2000L); // must sleep some time since the start up is being processed in a new thread verify(workerNodeService, times(4)).up(CREDENTIAL_UUID, "version", "123"); assertThat(workerManager.isUp()).isTrue(); }
Example #3
Source File: ApplicationEventListener.java From Almost-Famous with MIT License | 6 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { LOG.debug("初始化环境变量"); } else if (event instanceof ApplicationPreparedEvent) { LOG.debug("初始化完成"); LOG.debug("初始GameData策划数据"); String path = ApplicationEventListener.class.getResource("/gamedata").getFile(); ConfigManager.loadGameData(path); } else if (event instanceof ContextRefreshedEvent) { LOG.debug("应用刷新"); } else if (event instanceof ApplicationReadyEvent) { LOG.debug("应用已启动完成"); } else if (event instanceof ContextStartedEvent) { LOG.debug("应用启动,需要在代码动态添加监听器才可捕获"); } else if (event instanceof ContextStoppedEvent) { LOG.debug("应用停止"); } else if (event instanceof ContextClosedEvent) { ApplicationContext applicationContext = ((ContextClosedEvent) event).getApplicationContext(); grpcClient = applicationContext.getBean(GrpcClient.class); grpcClient.close(); LOG.debug("应用关闭"); } }
Example #4
Source File: ApplicationEventListener.java From Almost-Famous with MIT License | 6 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationEnvironmentPreparedEvent) { LOG.debug("初始化环境变量"); } else if (event instanceof ApplicationPreparedEvent) { LOG.debug("初始化完成"); LOG.debug("初始GameData策划数据"); ConfigManager.loadGameData(this.configPath); } else if (event instanceof ContextRefreshedEvent) { LOG.debug("应用刷新"); } else if (event instanceof ApplicationReadyEvent) { LOG.debug("应用已启动完成"); } else if (event instanceof ContextStartedEvent) { LOG.debug("应用启动,需要在代码动态添加监听器才可捕获"); } else if (event instanceof ContextStoppedEvent) { LOG.debug("应用停止"); } else if (event instanceof ContextClosedEvent) { ApplicationContext context = ((ContextClosedEvent) event).getApplicationContext(); rpcClient = context.getBean(RpcClient.class); rpcClient.close(); LOG.error("应用关闭"); } else { } }
Example #5
Source File: SpringShutdownHookThreadDemo.java From geekbang-lessons with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws IOException { GenericApplicationContext context = new GenericApplicationContext(); context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() { @Override public void onApplicationEvent(ContextClosedEvent event) { System.out.printf("[线程 %s] ContextClosedEvent 处理\n", Thread.currentThread().getName()); } }); // 刷新 Spring 应用上下文 context.refresh(); // 注册 Shutdown Hook context.registerShutdownHook(); System.out.println("按任意键继续并且关闭 Spring 应用上下文"); System.in.read(); // 关闭 Spring 应用(同步) context.close(); }
Example #6
Source File: BalancerConfiguration.java From haven-platform with Apache License 2.0 | 6 votes |
/** * Listens ContextClosedEvent and Closes all async http connections */ @Bean ApplicationListener<?> applicationListener() { return new SmartApplicationListener() { @Override public int getOrder() { return 0; } @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return ContextClosedEvent.class.isAssignableFrom(eventType); } @Override public boolean supportsSourceType(Class<?> sourceType) { return true; } @Override public void onApplicationEvent(ApplicationEvent event) { Closeables.close(proxyInstance); } }; }
Example #7
Source File: InBufferTest.java From score with Apache License 2.0 | 6 votes |
@Test(timeout = 5000) public void testRunBeforeCtxClosedEvent() throws Exception { ContextRefreshedEvent refreshEvent = mock(ContextRefreshedEvent.class); inBuffer.onApplicationEvent(refreshEvent); ContextClosedEvent event = mock(ContextClosedEvent.class); when(workerManager.isUp()).thenReturn(true); doReturn(true).when(workerStateUpdateService).isWorkerEnabled(); Thread thread = new Thread(inBuffer); thread.start(); verify(workerManager, timeout(1000).atLeastOnce()).getInBufferSize(); inBuffer.onApplicationEvent(event); while (thread.isAlive()) { Thread.sleep(100L); } }
Example #8
Source File: RuntimeExecBeansTest.java From alfresco-core with GNU Lesser General Public License v3.0 | 6 votes |
public void testBootstrapAndShutdown() throws Exception { // now bring up the bootstrap ApplicationContext ctx = new ClassPathXmlApplicationContext(APP_CONTEXT_XML); // the folder should be gone assertFalse("Folder was not deleted by bootstrap", dir.exists()); // now create the folder again dir.mkdir(); assertTrue("Directory not created", dir.exists()); // announce that the context is closing ctx.publishEvent(new ContextClosedEvent(ctx)); // the folder should be gone assertFalse("Folder was not deleted by shutdown", dir.exists()); }
Example #9
Source File: WireMockInitializer.java From blog-tutorials with MIT License | 6 votes |
@Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { WireMockServer wireMockServer = new WireMockServer(new WireMockConfiguration().dynamicPort()); wireMockServer.start(); configurableApplicationContext.getBeanFactory().registerSingleton("wireMockServer", wireMockServer); configurableApplicationContext.addApplicationListener(applicationEvent -> { if (applicationEvent instanceof ContextClosedEvent) { wireMockServer.stop(); } }); TestPropertyValues .of("todo_url:http://localhost:" + wireMockServer.port() + "/todos") .applyTo(configurableApplicationContext); }
Example #10
Source File: SleuthContextListener.java From spring-cloud-sleuth with Apache License 2.0 | 6 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent || event instanceof ContextClosedEvent) { if (log.isDebugEnabled()) { log.debug("Context refreshed or closed [" + event + "]"); } ApplicationContextEvent contextEvent = (ApplicationContextEvent) event; ApplicationContext context = contextEvent.getApplicationContext(); BeanFactory beanFactory = context; if (context instanceof ConfigurableApplicationContext) { beanFactory = ((ConfigurableApplicationContext) context).getBeanFactory(); } SleuthContextListener listener = CACHE.getOrDefault(beanFactory, this); listener.refreshed.compareAndSet(false, event instanceof ContextRefreshedEvent); listener.closed.compareAndSet(false, event instanceof ContextClosedEvent); CACHE.put(beanFactory, listener); } }
Example #11
Source File: WebasebeeApplication.java From WeBASE-Collect-Bee with Apache License 2.0 | 6 votes |
@Override public void onApplicationEvent(ContextClosedEvent contextClosedEvent) { if (this.connector == null) { return; } this.connector.pause(); Executor executor = this.connector.getProtocolHandler().getExecutor(); if (executor instanceof ThreadPoolExecutor) { try { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; threadPoolExecutor.shutdown(); if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) { log.warn("Tomcat 进程在" + waitTime + " 秒内无法结束,尝试强制结束"); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }
Example #12
Source File: RegistrationApplicationListenerTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void should_cancel_register_task_on_context_close() { ApplicationRegistrator registrator = mock(ApplicationRegistrator.class); ThreadPoolTaskScheduler scheduler = mock(ThreadPoolTaskScheduler.class); RegistrationApplicationListener listener = new RegistrationApplicationListener(registrator, scheduler); ScheduledFuture<?> task = mock(ScheduledFuture.class); when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)))).then((invocation) -> task); listener.onApplicationReady(new ApplicationReadyEvent(mock(SpringApplication.class), null, mock(ConfigurableWebApplicationContext.class))); verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10))); listener.onClosedContext(new ContextClosedEvent(mock(WebApplicationContext.class))); verify(task).cancel(true); }
Example #13
Source File: WorkerManagerTest.java From score with Apache License 2.0 | 6 votes |
@Test public void startUpWrongVersion() throws Exception { //shutting the service down workerManager.onApplicationEvent(mock(ContextClosedEvent.class)); assertThat(workerManager.isUp()).isFalse(); reset(workerNodeService); reset(engineVersionService); when(engineVersionService.getEngineVersionId()).thenReturn("666"); //starting it again workerManager.onApplicationEvent(mock(ContextRefreshedEvent.class)); Thread.sleep(1000L); // must sleep some time since the start up is being processed in a new thread assertThat(workerManager.isUp()).isFalse(); reset(engineVersionService); when(engineVersionService.getEngineVersionId()).thenReturn("123"); }
Example #14
Source File: DriversDeregister.java From cosmo with Apache License 2.0 | 6 votes |
@Override public void onApplicationEvent(ContextClosedEvent event) { LOG.info("[Drivers] About to de-register drivers..."); Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); LOG.info("[Drivers] De-registering {}", driver); try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { LOG.error("Failed to deregister driver: {}", driver.getClass()); } } LOG.info("[Drivers] De-registered drivers."); }
Example #15
Source File: GaeAppEventListener.java From gae with MIT License | 6 votes |
@Override public void onApplicationEvent(ApplicationContextEvent event) { // 上下文初始化完成时启动vertx if (event instanceof ContextRefreshedEvent) { startHttpServer(event.getApplicationContext()); } else if (event instanceof ContextClosedEvent) { // 上下文关闭时关闭vertx IndexIncrementLoader loader = event.getApplicationContext().getBean(IndexIncrementLoader.class); try { vertx.close(); if (null != loader) { loader.shutdown(); } } catch (Exception e) { e.printStackTrace(); } } }
Example #16
Source File: WorkerManagerTest.java From score with Apache License 2.0 | 5 votes |
@Test public void shutDown() { assertThat(workerManager.isUp()).isTrue(); reset(workerNodeService); //shut down workerManager.onApplicationEvent(mock(ContextClosedEvent.class)); assertThat(workerManager.isUp()).isFalse(); }
Example #17
Source File: CseApplicationListener.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (initEventClass.isInstance(event)) { if (applicationContext instanceof AbstractApplicationContext) { ((AbstractApplicationContext) applicationContext).registerShutdownHook(); } SCBEngine scbEngine = SCBEngine.getInstance(); //SCBEngine init first, hence we do not need worry that when other beans need use the //producer microserviceMeta, the SCBEngine is not inited. // String serviceName = RegistryUtils.getMicroservice().getServiceName(); // SCBEngine.getInstance().setProducerMicroserviceMeta(new MicroserviceMeta(serviceName).setConsumer(false)); // SCBEngine.getInstance().setProducerProviderManager(applicationContext.getBean(ProducerProviderManager.class)); // SCBEngine.getInstance().setConsumerProviderManager(applicationContext.getBean(ConsumerProviderManager.class)); // SCBEngine.getInstance().setTransportManager(applicationContext.getBean(TransportManager.class)); scbEngine.setFilterChainsManager(applicationContext.getBean(FilterChainsManager.class)); scbEngine.getConsumerProviderManager().getConsumerProviderList() .addAll(applicationContext.getBeansOfType(ConsumerProvider.class).values()); scbEngine.getProducerProviderManager().getProducerProviderList() .addAll(applicationContext.getBeansOfType(ProducerProvider.class).values()); scbEngine.addBootListeners(applicationContext.getBeansOfType(BootListener.class).values()); scbEngine.run(); } else if (event instanceof ContextClosedEvent) { if (SCBEngine.getInstance() != null) { SCBEngine.getInstance().destroy(); } } }
Example #18
Source File: ServiceStartAction.java From java-trader with Apache License 2.0 | 5 votes |
@Override public int execute(BeansContainer beansContainer, PrintWriter writer, List<KVPair> options) throws Exception { //解析参数 init(options); ExchangeableTradingTimes tradingTimes = Exchange.SHFE.detectTradingTimes("au", LocalDateTime.now()); if ( tradingTimes==null ) { writer.println(DateUtil.date2str(LocalDateTime.now())+" is not trading time"); return 1; } LocalDate tradingDay = null; if ( tradingTimes!=null) { tradingDay = tradingTimes.getTradingDay(); } long traderPid = getTraderPid(); if ( traderPid>0 ) { writer.println(DateUtil.date2str(LocalDateTime.now())+" Trader process is running: "+traderPid); return 1; } writer.println(DateUtil.date2str(LocalDateTime.now())+" Starting from config "+System.getProperty(TraderHomeUtil.PROP_TRADER_CONFIG_FILE)+", home: " + TraderHomeUtil.getTraderHome()+", trading day: "+tradingDay); saveStatusStart(); List<String> args = new ArrayList<>(); for(KVPair kv:options) { args.add(kv.toString()); } ConfigurableApplicationContext context = SpringApplication.run(appClass, args.toArray(new String[args.size()])); saveStatusReady(); statusFile.deleteOnExit(); context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() { @Override public void onApplicationEvent(ContextClosedEvent event) { synchronized(statusFile) { statusFile.notify(); } } }); synchronized(statusFile) { statusFile.wait(); } return 0; }
Example #19
Source File: NodeServiceImpl.java From java-trader with Apache License 2.0 | 5 votes |
@EventListener(ContextClosedEvent.class) public void onAppClose() { if ( wsConnState != ConnectionState.Disconnected ) { try{ sendMessage(new NodeMessage(MsgType.CloseReq)); }catch(Throwable t) {} closeWsSession(wsSession); } }
Example #20
Source File: Context.java From document-management-software with GNU Lesser General Public License v3.0 | 5 votes |
/** * Processes a newly incoming event on appropriated events that registered * itself on it * * @param event the event to process */ @Override public synchronized void onApplicationEvent(ApplicationEvent event) { if ((event instanceof ContextStartedEvent) || (event instanceof ContextRefreshedEvent)) { processEvents(SystemEventStatus.BEANS_AVAILABLE); } else if (event instanceof ContextClosedEvent) { processEvents(SystemEventStatus.SYSTEM_DESTORY); } }
Example #21
Source File: AutoConfiguration.java From krpc with Apache License 2.0 | 5 votes |
public void onApplicationEvent(ApplicationEvent event) { // System.out.println("boot onApplicationEvent called, event = " + event); if (event instanceof ContextRefreshedEvent) { int delayStart = SpringBootstrap.instance.getBootstrap().getAppConfig().getDelayStart(); SpringBootstrap.instance.getRpcApp().start(delayStart); } if (event instanceof ContextClosedEvent) { SpringBootstrap.instance.getRpcApp().stop(); log.info("krpc service port stopped"); } //System.out.println("boot onApplicationEvent called, event = " + event+" ended ----------- "); }
Example #22
Source File: TasksCleanupTest.java From genie with Apache License 2.0 | 5 votes |
/** * Make sure the thread pool scheduler is shutdown. */ @Test void canShutdown() { final ContextClosedEvent event = Mockito.mock(ContextClosedEvent.class); final TasksCleanup cleanup = new TasksCleanup(this.scheduler); cleanup.onShutdown(event); Mockito.verify(this.scheduler, Mockito.times(1)).shutdown(); }
Example #23
Source File: ContextEventAdapter.java From micronaut-spring with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(Object event) { if (event instanceof StartupEvent) { eventPublisher.publishEvent(new ContextStartedEvent( applicationContext )); } else if (event instanceof ShutdownEvent) { eventPublisher.publishEvent(new ContextClosedEvent( applicationContext )); } }
Example #24
Source File: InBufferTest.java From score with Apache License 2.0 | 5 votes |
@Test(timeout = 5000) public void testPollingBehaviourOnWorkerDisabled() throws Exception { System.setProperty("worker.inbuffer.capacity", "20"); try { doReturn(true).when(workerManager).isUp(); doReturn(false).when(workerStateUpdateService).isWorkerEnabled(); doReturn(1).when(workerManager).getInBufferSize(); doNothing().when(synchronizationManager).finishGetMessages(); doNothing().when(synchronizationManager).startGetMessages(); doReturn(false).when(workerConfigurationUtils).isNewInbuffer(); doReturn(0.1).when(workerConfigurationUtils).getWorkerMemoryRatio(); doReturn(Collections.emptyList()).when(queueDispatcher).poll(anyString(), anyInt(), anyLong()); inBuffer.init(); Thread thread = new Thread(inBuffer); thread.start(); // Wait 1 second Thread.sleep(1000); // stop InBuffer operation new Thread(() -> { ContextClosedEvent contextClosedEvent = mock(ContextClosedEvent.class); inBuffer.onApplicationEvent(contextClosedEvent); }).start(); // Wait for inbuffer to die while (thread.isAlive()) { Thread.sleep(50L); } verify(queueDispatcher, never()).poll(anyString(), anyInt(), anyLong()); verify(synchronizationManager, atLeastOnce()).finishGetMessages(); } finally { System.clearProperty("worker.inbuffer.capacity"); } }
Example #25
Source File: EurekaAutoServiceRegistration.java From spring-cloud-netflix with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof WebServerInitializedEvent) { onApplicationEvent((WebServerInitializedEvent) event); } else if (event instanceof ContextClosedEvent) { onApplicationEvent((ContextClosedEvent) event); } }
Example #26
Source File: RestartListener.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return ApplicationPreparedEvent.class.isAssignableFrom(eventType) || ContextRefreshedEvent.class.isAssignableFrom(eventType) || ContextClosedEvent.class.isAssignableFrom(eventType); }
Example #27
Source File: SoaShutdownListener.java From radar with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ContextClosedEvent event) { try{ servCacheService.stop(); instanceTimeOutCleaner.stop(); log.info("soa客户端关闭!"); } catch (Exception e) { log.error("soaclosederror",e); } }
Example #28
Source File: RadarClientShutdownListener.java From radar with Apache License 2.0 | 5 votes |
@Override public void onApplicationEvent(ContextClosedEvent event) { if ("true".equals(env.getProperty("radar.instance.registerSelf", "true"))) { try { DiscoveryClient.getInstance().deregister(); logger.info("注册退出!"); } catch (Exception e) { logger.error("deregister_error", e); } } }
Example #29
Source File: TestCseApplicationListener.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
@Test public void onApplicationEvent_close(@Mocked ContextClosedEvent contextClosedEvent) { SCBEngine scbEngine = SCBBootstrap.createSCBEngineForTest(); scbEngine.setStatus(SCBStatus.UP); CseApplicationListener listener = new CseApplicationListener(); listener.onApplicationEvent(contextClosedEvent); Assert.assertEquals(SCBStatus.DOWN, scbEngine.getStatus()); scbEngine.destroy(); }
Example #30
Source File: ShutdownIndicator.java From alfresco-data-model with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void onApplicationEvent(ApplicationContextEvent event) { if (event instanceof ContextClosedEvent && event.getSource() == applicationContext) { synchronized (this) { shuttingDown = true; } } }