目录

Spring - Custom Events in Spring

编写和发布您自己的自定义事件需要执行许多步骤。 按照本章中的说明编写,发布和处理Custom Spring Events。

脚步 描述
1 创建一个名为SpringExample的项目,并在创建的项目中的src文件夹下创建一个包com.iowiki 。 所有类都将在此包下创建。
2 使用Add External JARs选项添加所需的Spring库,如Spring Hello World Example章节中所述。
3 通过扩展ApplicationEvent创建一个事件类CustomEvent 。 该类必须定义一个默认构造函数,该构造函数应该从ApplicationEvent类继承构造函数。
4 一旦定义了事件类,就可以从任何类发布它,让我们说实现ApplicationEventPublisherAware EventClassPublisher 。 您还需要在XML配置文件中将此类声明为bean,以便容器可以将bean标识为事件发布者,因为它实现了ApplicationEventPublisherAware接口。
5 已发布的事件可以在类中处理,让我们说EventClassHandler实现ApplicationListener接口并为自定义事件实现onApplicationEvent方法。
6src文件夹下创建bean配置文件Beans.xml ,并在MainApp类中创建Spring应用程序。
7 最后一步是创建所有Java文件和Bean配置文件的内容并运行应用程序,如下所述。

这是CustomEvent.java文件的内容

package com.iowiki;
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.iowiki;
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.iowiki;
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.iowiki;
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.iowiki.CustomEventHandler"/>
   <bean id = "customEventPublisher" class = "com.iowiki.CustomEventPublisher"/>
</beans>

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

y Custom Event
y Custom Event
↑回到顶部↑
WIKI教程 @2018