spring自定义事件和事件监听器以及事件的发布-ApplicationEvent
2018-03-06 00:00
405 查看
进行spring自定义事件步骤:
1、继承ApplicationEvent自定义事件;
2、实现接口ApplicationListener定义事件监听器;
3、使用ApplicationContext来发布事件;
一、继承ApplicationEvent自定义事件
代码如下:
二、实现接口ApplicationListener定义事件监听器
代码如下:
三、使用ApplicationContext来发布事件
代码如下:
四、在main方法中new DemoPublisher进行发布(其中定义了EventConfig配置文件,用来自动扫描对应的包注入成bean对象)
main方法类代码如下:
配置类代码如下:
1、继承ApplicationEvent自定义事件;
2、实现接口ApplicationListener定义事件监听器;
3、使用ApplicationContext来发布事件;
一、继承ApplicationEvent自定义事件
代码如下:
/** * 自定义事件 * @author lyq */ public class DemoEvent extends ApplicationEvent { private String msg; public DemoEvent(Object source, String msg) { super(source); this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
二、实现接口ApplicationListener定义事件监听器
代码如下:
/** * 定义事件监听器 * 实现ApplicationListener接口,指定监听的事件类型 * onApplicationEvent对消息进行接受处理 * @author lyq */ @Component public class DemoEventListener implements ApplicationListener<DemoEvent> { @Override public void onApplicationEvent(DemoEvent demoEvent) { String msg = demoEvent.getMsg(); System.out.println("事件监听器监听到事件消息DemoEvent,消息内容为: "+msg); } }
三、使用ApplicationContext来发布事件
代码如下:
/** * 事件发布类 * 使用ApplicationContext来发布事件 * @author lyq */ @Component public class DemoPublisher { @Autowired ApplicationContext applicationContext; public void publish(String msg) { applicationContext.publishEvent(new DemoEvent(this, msg)); } }
四、在main方法中new DemoPublisher进行发布(其中定义了EventConfig配置文件,用来自动扫描对应的包注入成bean对象)
main方法类代码如下:
/** * @author lyq */ public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(EventConfig.class); DemoPublisher demoPublisher = applicationContext.getBean(DemoPublisher.class); demoPublisher.publish("我来发布消息"); applicationContext.close(); } }
配置类代码如下:
/** * @author lyq */ @Configuration @ComponentScan("com.wisely.highlight_spring4.ch2.event") public class EventConfig { }
相关文章推荐
- spring自定义事件和事件监听器以及事件的发布-ApplicationEvent
- springboot源码分析14-事件发布机制以及应用监听器
- spring 的事件发布以及监听器
- springboot源码分析14-事件发布机制以及应用监听器
- 在Spring中发布自定义事件
- 使用kafka作为springcloud bus的消息总线,以及如何自定义总线事件
- 对于spring 的自定义事件发布与监听
- H5 <audio> 音频标签自定义样式修改以及添加播放控制事件
- springboot整合cxf发布webservice以及调用的方法
- Android使用RecyclerView实现自定义列表、点击事件以及下拉刷新
- 一个Java写的自定义的事件监听器例子
- Spring 4.2框架中注释驱动的事件监听器详解
- Spring与Ehcache简单自定义监听器配置
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- 如何在自定义Listener(监听器)中使用Spring容器管理的bean
- Android实现RecyclerView自定义列表、点击事件以及下拉刷新
- 自定义dialog以及其监听事件
- C#如何创建自定义控件以及添加自定义属性和事件使用
- Spring中的自定义事件
- 004-spring-data-elasticsearch 3.0.0.0使用【二】-spring-data之定义方法、创建repository实例、从聚合根发布事件