javascript
Spring 中的事件处理
Spring 的核心是 ApplicationContext,它負責管理 beans 的完整生命周期。當加載 beans 時,ApplicationContext 發布某些類型的事件。例如,當上下文啟動時,ContextStartedEvent 發布,當上下文停止時,ContextStoppedEvent 發布。
通過 ApplicationEvent 類和 ApplicationListener 接口來提供在 ApplicationContext 中處理事件。如果一個 bean 實現 ApplicationListener,那么每次 ApplicationEvent 被發布到 ApplicationContext 上,那個 bean 會被通知。
常用的事件:
(1) ContextRefreshedEvent:ApplicationContext 被初始化或刷新時,該事件被發布。這也可以在 ConfigurableApplicationContext 接口中使用 refresh() 方法來發生。
(2) ContextStartedEvent:當使用 ConfigurableApplicationContext 接口中的 start() 方法啟動 ApplicationContext 時,該事件被發布。你可以調查你的數據庫,或者你可以在接受到這個事件后重啟任何停止的應用程序。
(3) ContextStoppedEvent:當使用 ConfigurableApplicationContext 接口中的 stop() 方法停止 ApplicationContext 時,發布這個事件。可以在接受到這個事件后做必要的清理的工作。
(4) ContextClosedEvent: 當使用 ConfigurableApplicationContext 接口中的 close() 方法關閉 ApplicationContext 時,該事件被發布。一個已關閉的上下文到達生命周期末端;它不能被刷新或重啟。
看個具體的例子:
public class HelloWorld {private String message;public void setMessage(String message){this.message = message;}public void getMessage(){System.out.println("Your Message : " + message);} }新建一個CStartEventHandler.java:
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");} }MainApp.java:
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();} }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"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="helloWorld" class="com.tutorialspoint.HelloWorld"><property name="message" value="Hello World!"/></bean><bean id="cStartEventHandler" class="com.sap.CStartEventHandler"/><bean id="cStopEventHandler" class="com.sap.CStopEventHandler"/></beans>執行應用,輸出:
ContextStartedEvent Received Your Message : Hello World! ContextStoppedEvent Received總結
以上是生活随笔為你收集整理的Spring 中的事件处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring 基于 Java 的配置 -
- 下一篇: 助学贷款提前还款怎么还 助学贷款提前还款