參考:https://blog.csdn.net/liyantianmin/article/details/81017960
如果容器中有一個ApplicationListener Bean,每當ApplicationContext發佈ApplicationEvent時,ApplicationListener Bean將自動被觸發。這種事件機制都必須需要程序顯示的觸發。其中spring有一些內置的事件,當完成某種操作時會發出某些事件動作。比如監聽ContextRefreshedEvent事件,當所有的bean都初始化完成並被成功裝載後會觸發該事件,實現ApplicationListener接口可以收到監聽動作,然後可以寫自己的邏輯。同樣事件可以自定義、監聽也可以自定義,完全根據自己的業務邏輯來處理。
序號 | 內置事件 | 描述 |
---|---|---|
1 | ContextRefreshedEventApplicationContext | 被初始化或刷新時,該事件被髮布。這也可以在 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處理用戶請求結束後,系統會自動觸發該事件。 |
實現監聽事件接口舉例
比如要監聽ContextRefreshedEvent的時可以實現ApplicationListener接口,並且傳入要監聽的事件
@Component
public class TestApplicationListener implements ApplicationListener<ContextRefreshedEvent>{
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
System.out.println(contextRefreshedEvent);
System.out.println("TestApplicationListener............................");
}
}
自定義監聽事件
可以自定義事件,然後做完業務處理後手動發出。同上集成某個監聽接口,接收到事件後進行業務處理
事件定義:
public class EmailEvent extends ApplicationEvent{
private String address;
private String text;
public EmailEvent(Object source, String address, String text){
super(source);
this.address = address;
this.text = text;
}
public EmailEvent(Object source) {
super(source);
}
//......address和text的setter、getter
}
監聽定義:
public class EmailNotifier implements ApplicationListener{
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof EmailEvent) {
EmailEvent emailEvent = (EmailEvent)event;
System.out.println("郵件地址:" + emailEvent.getAddress());
System.our.println("郵件內容:" + emailEvent.getText());
} else {
System.our.println("容器本身事件:" + event);
}
}
}
業務觸發
public class SpringTest {
public static void main(String args[]){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//創建一個ApplicationEvent對象
EmailEvent event = new EmailEvent("hello","[email protected]","This is a test");
//主動觸發該事件
context.publishEvent(event);
}
}
必須把實現ApplicationListener的類定義成bean