1. 程式人生 > 其它 >Spring 學習 之 事件處理

Spring 學習 之 事件處理

技術標籤:Springspringjava

Spring 中的事件處理

你已經看到了在所有章節中 Spring 的核心是ApplicationContext,它負責管理 beans 的完整生命週期。當載入 beans 時,ApplicationContext 釋出某些型別的事件。例如,當上下文啟動時,ContextStartedEvent 釋出,當上下文停止時,ContextStoppedEvent 釋出。

通過 ApplicationEvent 類和 ApplicationListener 介面來提供在 ApplicationContext 中處理事件。如果一個 bean 實現 ApplicationListener,那麼每次 ApplicationEvent 被髮布到 ApplicationContext 上,那個 bean 會被通知。

Spring 提供了以下的標準事件:

序號Spring 內建事件 & 描述
1

ContextRefreshedEvent

ApplicationContext 被初始化或重新整理時,該事件被髮布。這也可以在 ConfigurableApplicationContext 介面中使用 refresh() 方法來發生。

2

ContextStartedEvent

當使用 ConfigurableApplicationContext 介面中的 start() 方法啟動 ApplicationContext 時,該事件被髮布。你可以調查你的資料庫,或者你可以在接受到這個事件後重啟任何停止的應用程式。

3

ContextStoppedEvent

當使用 ConfigurableApplicationContext 介面中的 stop() 方法停止 ApplicationContext 時,釋出這個事件。你可以在接受到這個事件後做必要的清理的工作。

4

ContextClosedEvent

當使用 ConfigurableApplicationContext 介面中的 close() 方法關閉 ApplicationContext 時,該事件被髮布。一個已關閉的上下文到達生命週期末端;它不能被重新整理或重啟。

5

RequestHandledEvent

這是一個 web-specific 事件,告訴所有 bean HTTP 請求已經被服務。

由於 Spring 的事件處理是單執行緒的,所以如果一個事件被髮布,直至並且除非所有的接收者得到的該訊息,該程序被阻塞並且流程將不會繼續。因此,如果事件處理被使用,在設計應用程式時應注意。

監聽上下文事件

為了監聽上下文事件,一個 bean 應該實現只有一個方法onApplicationEvent()的 ApplicationListener 介面。因此,我們寫一個例子來看看事件是如何傳播的,以及如何可以用程式碼來執行基於某些事件所需的任務。

讓我們在恰當的位置使用 Eclipse IDE,然後按照下面的步驟來建立一個 Spring 應用程式:

步驟描述
1建立一個名稱為 SpringExample 的專案,並且在建立專案的src資料夾中建立一個包 com.tutorialspoint。
2使用 Add External JARs 選項,新增所需的 Spring 庫,解釋見 Spring Hello World Example 章節。
3在 com.tutorialspoint 包中建立 Java 類 HelloWorld、CStartEventHandler、CStopEventHandler 和 MainApp。
4src資料夾中建立 Bean 的配置檔案 Beans.xml。
5最後一步是建立的所有 Java 檔案和 Bean 配置檔案的內容,並執行應用程式,解釋如下所示。

這裡是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);
   }
}

下面是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");
   }
}

下面是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");
   }
}

下面是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();
   }
}

下面是配置檔案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/beans
    http://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.tutorialspoint.CStartEventHandler"/>

   <bean id="cStopEventHandler" 
         class="com.tutorialspoint.CStopEventHandler"/>

</beans>

結果

ContextStartedEvent Received
Your Message : Hello World!
ContextStoppedEvent Received

Spring 中的自定義事件

編寫和釋出自己的自定義事件有許多步驟。按照在這一章給出的說明來編寫,釋出和處理自定義 Spring 事件。

步驟描述
1建立一個名稱為 SpringExample 的專案,並且在建立專案的src資料夾中建立一個包 com.tutorialspoint。
2使用 Add External JARs 選項,新增所需的 Spring 庫,解釋見 Spring Hello World Example 章節。
3通過擴充套件ApplicationEvent,建立一個事件類 CustomEvent。這個類必須定義一個預設的建構函式,它應該從 ApplicationEvent 類中繼承的建構函式。
4一旦定義事件類,你可以從任何類中釋出它,假定 EventClassPublisher 實現了 ApplicationEventPublisherAware。你還需要在 XML 配置檔案中宣告這個類作為一個 bean,之所以容器可以識別 bean 作為事件釋出者,是因為它實現了 ApplicationEventPublisherAware 介面。
5釋出的事件可以在一個類中被處理,假定 EventClassHandler 實現了 ApplicationListener 介面,而且實現了自定義事件的 onApplicationEvent 方法。
6src資料夾中建立 bean 的配置檔案 Beans.xml 和 MainApp 類,它可以作為一個 Spring 應用程式來執行。
7最後一步是建立的所有 Java 檔案和 Bean 配置檔案的內容,並執行應用程式,解釋如下所示。

這個是CustomEvent.java檔案的內容:

package com.tutorialspoint;
import org.springframework.context.ApplicationEvent;
public class CustomEvent extends ApplicationEvent{ 
   public CustomEvent(Object source) {
      super(source);
   }
   public String toString(){
      return "My Custom Event";
   }
}

下面是CustomEventPublisher.java檔案的內容:

package com.tutorialspoint;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
public class CustomEventPublisher 
   implements ApplicationEventPublisherAware {
   private ApplicationEventPublisher publisher;
   public void setApplicationEventPublisher
              (ApplicationEventPublisher publisher){
      this.publisher = publisher;
   }
   public void publish() {
      CustomEvent ce = new CustomEvent(this);
      publisher.publishEvent(ce);
   }
}

下面是CustomEventHandler.java檔案的內容:

package com.tutorialspoint;
import org.springframework.context.ApplicationListener;
public class CustomEventHandler 
   implements ApplicationListener<CustomEvent>{
   public void onApplicationEvent(CustomEvent event) {
      System.out.println(event.toString());
   }
}

下面是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");    
      CustomEventPublisher cvp = 
      (CustomEventPublisher) context.getBean("customEventPublisher");
      cvp.publish();  
      cvp.publish();
   }
}

下面是配置檔案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/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id="customEventHandler" 
      class="com.tutorialspoint.CustomEventHandler"/>

   <bean id="customEventPublisher" 
      class="com.tutorialspoint.CustomEventPublisher"/>

</beans>

一旦你完成了建立源和 bean 的配置檔案後,我們就可以執行該應用程式。如果你的應用程式一切都正常,將輸出以下資訊:

My Custom Event
My Custom Event