標籤:private .config port org 代碼 cat 應該 imp info
Spring的核心是ApplicationContext,它管理bean的完整生命週期。ApplicationContext在載入bean時發布某些類型的事件。例如,ContextStartedEvent當上下文啟動,並公布ContextStoppedEvent當上下文停止出版。
ApplicationContext中的事件處理是通過ApplicationEvent類和ApplicationListener介面提供的。因此,如果bean實現了ApplicationListener,那麼每次將ApplicationEvent發布到ApplicationContext時,都會通知該bean。
Spring的事件處理是單線程的,因此如果事件被發布,除非所有接收者都收到訊息,否則流程將被阻止,流程將不會繼續。因此,如果要使用事件處理,在設計應用程式時應該小心。
監聽上下文事件
要監聽上下文事件,bean應該實現ApplicationListener介面,該介面只有一個onApplicationEvent()方法。因此,讓我們編寫一個樣本來查看事件如何傳播以及如何使代碼根據特定事件執行所需任務。
樣本:
(1)編寫HelloWorld.java
package com.tutorialspoint;public class HelloWorld { private String message; public void setMessage(String message){ this.message = message; } public void getMessage(){ System.out.println("Your Message : " + message); }}
(2)編寫CStartEventHandler.java
package com.tutorialspoint;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextStartedEvent;public class CStartEventHandler implements ApplicationListener<ContextStartedEvent>{ public void onApplicationEvent(ContextStartedEvent event) { System.out.println("ContextStartedEvent Received"); }}
(3)編寫CStopEventHandler.java
package com.tutorialspoint;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextStoppedEvent;public class CStopEventHandler implements ApplicationListener<ContextStoppedEvent>{ public void onApplicationEvent(ContextStoppedEvent event) { System.out.println("ContextStoppedEvent Received"); }}
(4)編寫MainApp.java
package com.tutorialspoint;import org.springframework.context.ConfigurableApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;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(); }}
(5)編寫Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <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"/> </beans>
(6)運行MainApp.java中的main方法,結果如下:
Spring(九)之事件處理