某些情況下我們需要在 Spring Boot 容器啟動(dòng)加載完后執(zhí)行一些操作,此時(shí)可以通過(guò)實(shí)現(xiàn) ApplicationListener<E extends ApplicationEvent> 接口,并指定相應(yīng)事件來(lái)執(zhí)行操作,例如啟動(dòng)某些自定義守護(hù)線程
ApplicationContextEvent 是由 ApplicationContext 引發(fā)的事件基類(lèi),它有幾個(gè)實(shí)現(xiàn)類(lèi):
ContextRefreshedEvent :ApplicationContext 容器初始化或者刷新時(shí)觸發(fā)該事件,執(zhí)行一次
ContextStartedEvent :當(dāng)使用 ConfigurableApplicationContext 接口的 start() 方法啟動(dòng) ApplicationContext 容器時(shí)觸發(fā)該事件
ContextClosedEvent :當(dāng)使用 ConfigurableApplicationContext 接口的 close() 方法關(guān)閉 ApplicationContext 容器時(shí)觸發(fā)該事件
ContextStopedEvent : 當(dāng)使用 ConfigurableApplicationContext 接口的 stop() 方法停止 ApplicationContext 容器時(shí)觸發(fā)該事件
代碼例子
1
2
3
4
5
6
7
|
@Component public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println( "容器初始化或者刷新時(shí)觸發(fā)該事件,執(zhí)行一次" ); } } |
總結(jié)
以上所述是小編給大家介紹的Spring Boot容器加載時(shí)執(zhí)行特定操作,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.jianshu.com/p/cc6ab5337cd5