你已經看到了在全部章節中 Spring 的核心是 ApplicationContext,它負責管理 beans 的完整生命週期。當加載 beans 時,ApplicationContext 發佈某些類型的事件。例如,當上下文啓動時,ContextStartedEvent 發佈,當上下文中止時,ContextStoppedEvent 發佈。html
經過 ApplicationEvent 類和 ApplicationListener 接口來提供在 ApplicationContext 中處理事件。若是一個 bean 實現 ApplicationListener,那麼每次 ApplicationEvent 被髮布到 ApplicationContext 上,那個 bean 會被通知。web
序號spring |
Spring 內置事件 & 描述數據庫 |
1spa |
ContextRefreshedEvent線程 ApplicationContext 被初始化或刷新時,該事件被髮布。這也能夠在 ConfigurableApplicationContext 接口中使用 refresh() 方法來發生。設計 |
2code |
ContextStartedEventxml 當使用 ConfigurableApplicationContext 接口中的 start() 方法啓動 ApplicationContext 時,該事件被髮布。你能夠調查你的數據庫,或者你能夠在接受到這個事件後重啓任何中止的應用程序。htm |
3 |
ContextStoppedEvent 當使用 ConfigurableApplicationContext 接口中的 stop() 方法中止 ApplicationContext 時,發佈這個事件。你能夠在接受到這個事件後作必要的清理的工做。 |
4 |
ContextClosedEvent 當使用 ConfigurableApplicationContext 接口中的 close() 方法關閉 ApplicationContext 時,該事件被髮布。一個已關閉的上下文到達生命週期末端;它不能被刷新或重啓。 |
5 |
RequestHandledEvent 這是一個 web-specific 事件,告訴全部 bean HTTP 請求已經被服務。 |
因爲 Spring 的事件處理是單線程的,因此若是一個事件被髮布,直至而且除非全部的接收者獲得的該消息,該進程被阻塞而且流程將不會繼續。所以,若是事件處理被使用,在設計應用程序時應注意。
爲了監聽上下文事件,一個 bean 應該實現只有一個方法 onApplicationEvent() 的 ApplicationListener 接口。所以,咱們寫一個例子來看看事件是如何傳播的,以及如何能夠用代碼來執行基於某些事件所需的任務。
讓咱們在恰當的位置使用 Eclipse IDE,而後按照下面的步驟來建立一個 Spring 應用程序:
public class CStartEventHandler implements ApplicationListener<ContextStartedEvent>{ //容器啓動事件 public void onApplicationEvent(ContextStartedEvent event) { System.out.println("ContextStartedEvent Received"); } }
public class CStopEventHandler implements ApplicationListener<ContextStoppedEvent>{ public void onApplicationEvent(ContextStoppedEvent event) { System.out.println("ContextStoppedEvent Received"); } }
public class MainApp { public static void main(String[] args) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); // Let us raise a start event. context.start(); HelloWorld obj = (HelloWorld) context.getBean("helloWorld"); obj.getMessage(); // Let us raise a stop event. context.stop(); } }
<bean id="helloWorld" class="com.tutorialspoint.HelloWorld"> <property name="message" value="Hello World!"/> </bean> <bean id="cStartEventHandler" class="com.tutorialspoint.CStartEventHandler"/> <bean id="cStopEventHandler" class="com.tutorialspoint.CStopEventHandler"/>