Spring Boot 事件监听
2017-09-23 本文已影响2209人
每天学点编程
请关注我的微信公众号

技术交流群 (仅作技术交流):642646237
请关注我的头条号:

事件流程
1.自定义事件,一般是继承ApplicationEvent
抽象类;
2.自定义事件监听器,一般是实现ApplicationListener
接口;
3.启动的时候,需要把监听器加入到spring容器中;
4.发布事件,使用ApplicationContext.publishEvent
发布事件;
Spring Boot事件监听的例子
下面的实例是按照 事件流程 中的说明进行的。
第一步,自定事件,继承了ApplicationEvent
抽象类:

第二步,自定义事件监听器,实现
ApplicationListener
接口:
第三步,启动的时候,需要把监听器加入到spring容器中:

第四步,发布事件,使用
ApplicationContext.publishEvent
发布事件:
入口程序完整的代码如下:

配置监听器——org.springframework.boot.SpringApplication.addListeners(ApplicationListener<?>...)
添加监听器

配置监听器——把监听器纳入到spring容器中管理

需要注意的是
MyApplicationListener
是在com.maijunjin.springboot.springboot_start_listener.listener
中,所以需要修改App
所在的包为com.maijunjin.springboot.springboot_start_listener
。
配置监听器——使用context.listener.classes
配置项配置

配置监听器——使用@EventListener
注解,在方法上面加入@EventListener
注解,且该类需要纳入到spring容器中管理

需要注意方法的参数,请观察一下运行结果:

参数为MyApplicationEvent
类型的只运行了一次,而参数类型为Object
的运行了几次。
对 配置监听器——使用context.listener.classes
配置项配置 方式进行解析
是通过org.springframework.boot.context.config.DelegatingApplicationListener
类实现的,

在spring boot启动的过程中会触发ApplicationEnvironmentPreparedEvent
事件:

PROPERTY_NAME
的值为 "context.listener.classes"
更具体的细节请自行查看。
对 配置监听器——使用@EventListener
注解,在方法上面加入@EventListener
注解,且该类需要纳入到spring容器中管理 详解
具体细节请查看
org.springframework.context.event.EventListenerMethodProcessor
类。
下面只勾画出几个重点的地方:

下面的代码获取所有被@EventListener
注解的方法:

下面的代码根据该方法生成ApplicationListener
对象,并加入到Spring容器中

Spring boot中自带的事件

spring中自带的事件

下面测试一下org.springframework.context.event.ContextStoppedEvent
事件

context.stop();
会触发ContextStoppedEvent
事件:
