javascript
Spring 框架中有哪些不同类型的事件?
Spring 的ApplicationContext 提供了支持事件和代碼中監聽器的功能。
我們可以創建bean 用來監聽在ApplicationContext 中發布的事件。ApplicationEvent 類和在ApplicationContext 接口中處理的事件,如果一個bean 實現了ApplicationListener 接口,當一個ApplicationEvent 被發布以后,bean 會自動被通知。
public class AllApplicationEventListener implements ApplicationListener<ApplicationEvent> {@Overridepublic void onApplicationEvent(ApplicationEvent applicationEvent) {//process event} }Spring 提供了以下5 中標準的事件:
1.上下文更新事件(ContextRefreshedEvent):該事件會在ApplicationContext 被初始化或者更新時發布。也可以在調用ConfigurableApplicationContext 接口中的refresh()方法時被觸發。
2.上下文開始事件(ContextStartedEvent):當容器調用ConfigurableApplicationContext 的Start()方法開始/重新開始容器時觸發該事件。
3.上下文停止事件(ContextStoppedEvent):當容器調用ConfigurableApplicationContext 的Stop()方法停止容器時觸發該事件。
4.上下文關閉事件(ContextClosedEvent):當ApplicationContext 被關閉時觸發該事件。容器被關閉時,其管理的所有單例Bean 都被銷毀。
5.請求處理事件(RequestHandledEvent):在Web 應用中,當一個http 請求(request)結束觸發該事件。
除了上面介紹的事件以外,還可以通過擴展ApplicationEvent 類來開發自定義的事件。
public class CustomApplicationEvent extends ApplicationEvent {public CustomApplicationEvent ( Object source, final String msg ){super(source);System.out.println("Created a Custom event");} }為了監聽這個事件,還需要創建一個監聽器:
public class CustomEventListener implements ApplicationListener < CustomApplicationEvent >{@Overridepublic void onApplicationEvent(CustomApplicationEvent applicationEvent) {} }之后通過applicationContext 接口的publishEvent()方法來發布自定義事件。
CustomApplicationEvent customEvent = new CustomApplicationEvent(applicationContext,“Test message”);
applicationContext.publishEvent(customEvent);
?
總結
以上是生活随笔為你收集整理的Spring 框架中有哪些不同类型的事件?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 构造方法注入和设值注入有什么区别?
- 下一篇: 在Spring 框架中如何更有效的使用J