Spring 中的自定義事件



編寫和釋出您自己的自定義事件需要採取許多步驟。請按照本章中提供的說明來編寫、釋出和處理自定義 Spring 事件。

步驟 描述
1 建立一個名為SpringExample的專案,並在建立的專案中 src 資料夾下建立一個名為com.tutorialspoint的包。所有類都將在此包下建立。
2 使用新增外部 JAR選項新增所需的 Spring 庫,如Spring Hello World 示例章節中所述。
3 建立一個事件類CustomEvent,繼承自ApplicationEvent。此類必須定義一個預設建構函式,該建構函式應繼承自 ApplicationEvent 類的建構函式。
4 定義好事件類後,您可以從任何類中釋出它,例如EventClassPublisher,它實現了ApplicationEventPublisherAware。您還需要在 XML 配置檔案中將此類宣告為一個 Bean,以便容器可以識別該 Bean 為事件釋出者,因為它實現了 ApplicationEventPublisherAware 介面。
5 已釋出的事件可以在一個類中處理,例如EventClassHandler,它實現了ApplicationListener介面併為自定義事件實現了onApplicationEvent方法。
6 src資料夾下建立 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 配置檔案後,讓我們執行應用程式。如果應用程式一切正常,它將列印以下訊息:-

y Custom Event
y Custom Event
廣告