1. 使用場景:在一些業務場景中,當容器初始化完成之后,需要處理一些操作,比如一些數據的加載、初始化緩存、特定任務的注冊、開啟線程或程序來干某些事情等等。
2. 使用步驟:
A. 監聽類實現ApplicationListener
接口 ;
B. 將監聽類添加到SpringApplication
實例(兩種方式:application.properties配置、java啟動配置)。
3. 支持的事件類型:
A. ApplicationStartedEvent —— spring boot啟動開始時執行的事件;
B. ApplicationEnvironmentPreparedEvent —— spring boot 對應Enviroment已經准備完畢,但此時上下文context還沒有創建;
C. ApplicationPreparedEvent —— spring boot上下文context創建完成,但此時spring中的bean是沒有完全加載完成的;
D. ApplicationFailedEvent —— spring boot啟動異常時執行事件 。
4.Spring內置的事件:
A. ContextRefreshedEvent —— ApplicationContext容器初始化或者刷新時觸發該事件;
B. ContextStartedEvent —— 當使用ConfigurableApplicationContext接口的start()方法啟動ApplicationContext容器時觸發該事件;
C. ContextClosedEvent —— 當使用ConfigurableApplicationContext接口的close()方法關閉ApplicationContext容器時觸發該事件;
D. ContextStopedEvent —— 當使用ConfigurableApplicationContext接口的stop()方法停止ApplicationContext容器時觸發該事件。
5.舉例說明:
package com.ruhuanxingyun; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.nsac.business.listener.ApplicationStartup; @SpringBootApplication public class SpApp { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(SpApp.class); springApplication.addListeners(new ApplicationStartup()); springApplication.run(args); } }
package com.nsac.ruhuanxingyun; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
@Override public void onApplicationEvent(ContextRefreshedEvent event) { ApplicationContext ac = event.getApplicationContext(); StepExecutor StepExecutor = new StepExecutor(ac.getEnvironment().getProperty("project-id"), ac.getBean("businessSingleJedisPool",redis.clients.jedis.JedisPool.class),
ac.getBean("redisCluster", redis.clients.jedis.JedisCluster.class)); Thread thread = new Thread(StepExecutor); thread.start(); } }
可參考:https://blog.csdn.net/liaokailin/article/details/48186331