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