spring-ApplicationContext的事件机制
spring-ApplicationContext的事件机制
1.通过ApplicationEvent类和ApplicationListener接口,可以实现ApplicationContext的事件处理。
如果容器中有一个ApplicationListener bean,当ApplicationContext发布ApplicationEvent时,ApplicationListener bean将自动被触发。
2.spring的事件框架的两个重要成员(即Event、Listener):
ApplicationEvent:容器事件,必须由ApplicationContext发布。
ApplicationListener:监听器,可由容器中的任何监听器bean担任。
事件机制中的3要素:事件源(ApplicationContext)、事件(Event)、事件监听器(Listener)。
Event事件——>ApplicationContext事件源发布事件——>触发Listener监听器——>监听器执行内部onApplicationEvent(ApplicationEvent e)方法,
Event事件作为传入参数。
由上面的流程可知,只需要在容器中注册实现了ApplicationListener的bean,当ApplicationContext发布事件的时候,就会被监听器自动捕获了。
3.注册事件监听器并实现ApplicationListener接口的简单PreReturnTriggerEvent.java示例代码如下:
@Component
@Slf4j
public class PreReturnListener implements ApplicationListener<PreReturnTriggerEvent> {
@Resource
private PreReturnProductService preReturnProductService;
@Override
public void onApplicationEvent(PreReturnTriggerEvent event) {
log.info("触发同步待还信息事件");
if (ObjectUtils.isEmpty(event.getStoreId())){
return;
}
//业务=========
preReturnProductService.syncPerReturnData(event.getStoreId());
}
}
4.继承ApplicationEvent的简单事件java bean举例PreReturnTriggerEvent.java
public class PreReturnTriggerEvent extends ApplicationEvent {
private Long storeId;
private TriggerEventEnum triggerEvent;
public PreReturnTriggerEvent(Object source, Long storeId, TriggerEventEnum triggerEvent) {
super(source);
this.storeId = storeId;
this.triggerEvent = triggerEvent;
}
public TriggerEventEnum getTriggerEvent() {
return triggerEvent;
}
public void setTriggerEvent(TriggerEventEnum triggerEvent) {
this.triggerEvent = triggerEvent;
}
public Long getStoreId() {
return storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
}
}
- 实战ApplicationContext事件源演示,用于发布事件,触发监听器执行处理:
@Resource
ApplicationContext applicationContext;
try {
//触发待还信息统计
ExecutorService executorService = Executors.newFixedThreadPool(1);
executorService.execute(()->{
applicationContext.publishEvent(new PreReturnTriggerEvent(applicationContext,Long.valueOf(req.getStoreId()), TriggerEventEnum.RETURNED));
});
} catch (Exception e) {
log.warn("publishEvent PreReturnTriggerEvent error:{}",e);
}
6.spring的提供的内置事件:
1》ontextRefreshedEvent:ApplicationContext容器初始化或刷新触发该事件。此处说的初始化,是指所有的bean被成功加载,后处理的 bean被检测激活,所有的singleton bean被预初始化,ApplicationContext容器已就绪可用
2》ContextStartdEvent:当使用ApplicationContext的子接口ConfigurableApplicationContex接口的start()方法启动ApplicationContext容器时触发该事件。容器管理生命周期的bean实例将获得一个指定的启动信号,这在经常需要停止后重新启动的场合比较常见。
3》ContextClossedEvent:当使用ConfigurableApplicationContex接口的close()方法关闭ApplicationContext容器时触发该事件。
4》ContextStoppedEvent:当使用ConfigurableApplicationContex接口的stop()方法使ApplicationContext容器停止时触发该事件 。此处的“停止”意味着,容器管理生命周期的bean实例将获得一个指定的停止信号。被停止的spring容器可以再次通过调用start()方法重新启动。
5》RequestHandledEvent:Web相关的事件,只能应用于使用DispatcherServlet的Web应用中。在使用spring作为前端的MVC控制器时,当spring处理用户请求结束后,系统会自动触发该事件。