Spring(九)之事件處理
阿新 • • 發佈:2018-08-11
xmla hello 查看 cst 以及 mes tor ica edev 因此,如果要使用事件處理,在設計應用程序時應該小心。
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(九)之事件處理