扫码一下
查看教程更方便
本篇我们介绍Spring 中的自定义事件,编写和发布自己的自定义事件需要执行多个步骤。 按照本章给出的说明编写、发布和处理自定义 Spring 事件。
这是 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<CustomEvent> { 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
<?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.jiyik.CustomEventHandler"/> <bean id = "customEventPublisher" class = "com.jiyik.CustomEventPublisher"/> </beans>
完成源代码和 bean 配置文件后,让我们运行应用程序。 如果应用程序一切正常,它将打印以下消息
y Custom Event
y Custom Event