Spring 中的自定义事件
编写和发布您自己的自定义事件需要执行多个步骤。 按照本章给出的说明编写、发布和处理自定义 Spring 事件。
| 步骤 | 描述 |
|---|---|
| 1 | 创建一个名为 SpringExample 的项目,并在创建的项目中的 src 文件夹下创建一个包 com.tutorialspoint。 All the classes will be created under this package. |
| 2 | 使用 Add External JARs 选项添加所需的 Spring 库,如 Spring Hello World 示例 一章中所述。 |
| 3 | 通过扩展 ApplicationEvent 创建一个事件类 CustomEvent。 此类必须定义一个默认构造函数,该构造函数应从 ApplicationEvent 类继承构造函数。 |
| 4 | 一旦定义了事件类,您就可以从任何类发布它,例如实现 ApplicationEventPublisherAware 的 EventClassPublisher。 您还需要在 XML 配置文件中将此类声明为 bean,以便容器可以将 bean 标识为事件发布者,因为它实现了 ApplicationEventPublisherAware 接口。 |
| 5 | 一个发布的事件可以在一个类中处理,比如说EventClassHandler,它实现了ApplicationListener接口,并为自定义事件实现了onApplicationEvent方法。 |
| 6 | 在 src 文件夹下创建 Beans 配置文件 Beans.xml。and a MainApp class which will work as Spring application. |
| 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

