下面通过一个具体的例子来说明如何创建自定义事件:
CustomEvent.java
package com.soygrow.CustomEvent;
import org.springframework.context.ApplicationEvent;
public class CustomEvent extends ApplicationEvent {
public CustomEvent(Object source) {
super(source);
}
public String toString() {
return "My Custom Event";
}
}
扩展ApplicationEvent,创建自定义事件类CustomEvent,这个类必须有一个默认构造函数,并实现父类的构造。
CustomEventPublisher.java
package com.soygrow.CustomEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
public class CustomEventPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher publisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
public void publish() {
CustomEvent ce = new CustomEvent(this);
publisher.publishEvent(ce);
}
}
自定义事件定义成功后,你可以从任何类中发布它,所以需要实现ApplicationEventPublisherAware接口
CustomEventHandler.java
package com.soygrow.CustomEvent;
import org.springframework.context.ApplicationListener;
public class CustomEventHandler implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent customEvent) {
System.out.println(customEvent.toString());
}
}
上面代码是发布一个事件。
MainApp.java
package com.soygrow.CustomEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("CustomEventBeans.xml");
CustomEventPublisher cvp =
(CustomEventPublisher) context.getBean("customEventPublisher");
cvp.publish();
cvp.publish();
}
}
CustomEventBeans.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.xsd">
<bean id="customEventHandler" class="com.soygrow.CustomEvent.CustomEventHandler"/>
<bean id="customEventPublisher" class="com.soygrow.CustomEvent.CustomEventPublisher"/>
</beans>
如果一切正常,那么运行的结果是:
My Custom Event
My Custom Event