您的位置:首页 > 编程语言 > Java开发

Spring学习九:自定义事件

2017-05-10 00:17 190 查看

学习目标

Spring自定义事件如何编写

Spring自定义事件如何使用

如何编写

继承ApplicationEvent

继承ApplicationEvent类,创建一个自定义的事件类

这个类必须定义一个默认的构造函数,它应该从 ApplicationEvent 类中继承的构造函数。

public class CustomEvent extends ApplicationEvent{
public CustomEvent(Object source) {
super(source);
}
public String toString(){
return "My Custom Event";
}
}


实现ApplicationEventPublisherAware

实现ApplicationEventPublisherAware类,创建一个发布事件类的类

在 XML 配置文件中声明这个类作为一个 bean之所以容器可以识别bean 作为事件发布者,是因为它实现了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);
}
}


实现了 ApplicationListener

实现了 ApplicationListener 接口,定义的事件类在此触发。

实现了自定义事件的 onApplicationEvent 方法

public class CustomEventHandler
implements ApplicationListener<CustomEvent>{
public void onApplicationEvent(CustomEvent event) {
System.out.println(event.toString());
}
}


3.创建的所有 Java 文件和 Bean 配置文件的内容

<?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>


使用

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();
}
}


总结

事件的编写需要写的3个类

程序运行的执行顺序。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: