日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring 中的事件处理

發布時間:2023/12/19 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 中的事件处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。