ApplicationListener詳解
ApplicationListener可以監聽某個事件event
通過實現這個接口,傳入一個泛型事件,在run方法中就可以監聽這個事件,從而做出一定的邏輯
比如在等所有bean加載完之后執行某些操作
public class SystemListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().getParent() == null) { System.out.println("do something"); } } }
Spring內置事件
1、ContextRefreshedEvent
ApplicationContext 被初始化或刷新時,該事件被發布。這也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法來發生。此處的初始化是指:所有的Bean被成功裝載,后處理Bean被檢測並激活,所有Singleton Bean 被預實例化,ApplicationContext容器已就緒可用
2、ContextStartedEvent
當使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法啟動 ApplicationContext 時,該事件被發布。你可以調查你的數據庫,或者你可以在接受到這個事件后重啟任何停止的應用程序
3、ContextStoppedEvent
當使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 時,發布這個事件。你可以在接受到這個事件后做必要的清理的工作
4、ContextClosedEvent
當使用 ConfigurableApplicationContext 接口中的 close() 方法關閉 ApplicationContext 時,該事件被發布。一個已關閉的上下文到達生命周期末端;它不能被刷新或重啟
5、RequestHandledEvent
這是一個 web-specific 事件,告訴所有 bean HTTP 請求已經被服務。只能應用於使用DispatcherServlet的Web應用。在使用Spring作為前端的MVC控制器時,當Spring處理用戶請求結束后,系統會自動觸發該事件