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个类程序运行的执行顺序。
相关文章推荐
- spring学习教程8-自定义属性编辑器PropertyEditor 和自定义事件
- 自定义事件的学习
- Spring通过容器获取配置对象及事件注入(学习笔记二)
- javascript 学习之自定义滚动条加滚轮事件
- IOS 学习---通过block自定义button的点击事件
- iOS学习笔记(3)——响应自定义的UITableViewCell及其内部控件的点击事件
- Spring学习-webcontex的自动配置和事件传播机制及使用
- Android-UI布局---RecyclerView学习(一)在适配器中自定义长按和点击事件
- spring 自定义标签 学习
- jQuery 自定义事件的学习笔记
- spring学习笔记--在自定义servlet中获取到spring的applicationcontext
- Qt 学习(8)Qt Creator中鼠标键盘事件的处理实现自定义鼠标指针(转)
- (精)Spring IOC核心源码学习III:bean标签和自定义标签实现原理
- jquery学习之-阻止事件冒泡,触发自定义事件
- spring 自定义标签 学习二
- 学习WF笔记9- 自定义活动中事件类型的属性(3)
- IssueVision 学习笔记(二)-----为控件添加自定义属性和事件
- 案例学习BlazeDS+Spring之四InSync02使用RemoteObject事件
- 2014-10-27Android学习------布局处理(八)------自定义ListView的监听事件和Adapter的实现-----城市列表应用程序
- spring自定义schema学习