教程 > spring 框架 > 阅读:35

spring 中的自定义事件——迹忆客-ag捕鱼王app官网

本篇我们介绍spring 中的自定义事件,编写和发布自己的自定义事件需要执行多个步骤。 按照本章给出的说明编写、发布和处理自定义 spring 事件。

  1. 使用我们在spring 第一个示例创建的项目 firstspring。
  2. 通过扩展 applicationevent 创建一个事件类 customevent。 此类必须定义一个默认构造函数,该构造函数应从 applicationevent 类继承构造函数。
  3. 一旦定义了事件类,就可以从任何类中发布它,比如实现 applicationeventpublisheraware 的 eventclasspublisher。 我们还需要在 xml 配置文件中将此类声明为 bean,以便容器可以将 bean 识别为事件发布者,因为它实现了 applicationeventpublisheraware 接口。
  4. 发布的事件可以在一个类中被处理,假定 eventclasshandler 实现了 applicationlistener 接口,而且实现了自定义事件的 onapplicationevent 方法。
  5. 在 src 文件夹中创建 bean 的配置文件 beans.xml 和 mainapp 类,它可以作为一个 spring 应用程序来运行。
  6. 最后一步是创建的所有 java 文件和 bean 配置文件的内容,并运行应用程序,解释如下所示。

这是 customevent.java 文件的内容

customevent.java

package com.jiyik;
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 文件的内容

customeventpublisher.java

package com.jiyik;
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 文件的内容

customeventhandler.java

package com.jiyik;
import org.springframework.context.applicationlistener;
public class customeventhandler implements applicationlistener {
   public void onapplicationevent(customevent event) {
      system.out.println(event.tostring());
   }
}

以下是 mainapp.java 文件的内容

mainapp.java

package com.jiyik;
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

beans.xml



   
   

完成源代码和 bean 配置文件后,让我们运行应用程序。 如果应用程序一切正常,它将打印以下消息

y custom event
y custom event

查看笔记

扫码一下
查看教程更方便
网站地图