Spring事件监听机制
前言
Spring中的事件机制其实就是设计模式中的观察者模式,主要由以下角色构成:
- 事件
- 事件监听器(监听并处理事件)
- 事件发布者(发布事件)
首先看一下监听器和发布者的接口定义
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
void onApplicationEvent(E event);
}
public interface ApplicationEventPublisher {
default void publishEvent(ApplicationEvent event) {
publishEvent((Object) event);
}
void publishEvent(Object event);
}
事件流转流程
初始化事件广播器
看一下这个方法AbstractApplicationContext.refresh
,在IOC源码解析那篇文章已经把这个方法分析完了,所以直接关注事件广播器和事件发布相关的逻辑即可
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// 初始化事件广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// 发布事件
finishRefresh();
}
catch (BeansException ex) {
logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
可以看到如果没有自定义的事件广播器,默认是使用SimpleApplicationEventMulticaster
的
发布事件
发布事件是在bean的初始化之后的
protected void finishRefresh() {
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// 发布事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
public void publishEvent(ApplicationEvent event) {
Assert.notNull(event, "Event must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Publishing event in " + getDisplayName() + ": " + event);
}
//1. 获取到事件广播器,发布事件
getApplicationEventMulticaster().multicastEvent(event);
//2. 如果存在父容器,父容器也将发布事件
if (this.parent != null) {
this.parent.publishEvent(event);
}
}
具体的发布逻辑在multicastEvent
方法中
public void multicastEvent(final ApplicationEvent event) {
//遍历执行listener,getApplicationListeners调用AbstractApplicationEventMulticaster父类方法
for (final ApplicationListener listener : getApplicationListeners(event)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(new Runnable() {
@Override
public void run() {
listener.onApplicationEvent(event);
}
});
}
else {
listener.onApplicationEvent(event);
}
}
}
可以看到也没啥特殊的,无非就是起个线程池去调用这些监听器的方法
而监听器的处理就看各个监听器的具体实现了
Spring事件监听机制的更多相关文章
- Spring 事件监听机制及原理分析
简介 在JAVA体系中,有支持实现事件监听机制,在Spring 中也专门提供了一套事件机制的接口,方便我们实现.比如我们可以实现当用户注册后,给他发送一封邮件告诉他注册成功的一些信息,比如用户订阅的主 ...
- Spring事件监听机制源码解析
Spring事件监听器使用 1.Spring事件监听体系包括三个组件:事件.事件监听器,事件广播器. 事件:定义事件类型和事件源,需要继承ApplicationEvent. package com.y ...
- SpringBoot事件监听机制及观察者模式/发布订阅模式
目录 本篇要点 什么是观察者模式? 发布订阅模式是什么? Spring事件监听机制概述 SpringBoot事件监听 定义注册事件 注解方式 @EventListener定义监听器 实现Applica ...
- Spring ApplicationContext(八)事件监听机制
Spring ApplicationContext(八)事件监听机制 本节则重点关注的是 Spring 的事件监听机制,主要是第 8 步:多播器注册:第 10 步:事件注册. public void ...
- Spring的事件监听机制
最近公司在重构广告系统,其中核心的打包功能由广告系统调用,即对apk打包的调用和打包完成之后的回调,需要提供相应的接口给广告系统.因此,为了将apk打包的核心流程和对接广告系统的业务解耦,利用了spr ...
- 7_3.springboot2.x启动配置原理_3.事件监听机制
事件监听机制配置在META-INF/spring.factories ApplicationContextInitializer SpringApplicationRunListenerioc容器中的 ...
- SpringBoot事件监听机制源码分析(上) SpringBoot源码(九)
SpringBoot中文注释项目Github地址: https://github.com/yuanmabiji/spring-boot-2.1.0.RELEASE 本篇接 SpringApplicat ...
- Halo 开源项目学习(六):事件监听机制
基本介绍 Halo 项目中,当用户或博主执行某些操作时,服务器会发布相应的事件,例如博主登录管理员后台时发布 "日志记录" 事件,用户浏览文章时发布 "访问文章" ...
- 4.JAVA之GUI编程事件监听机制
事件监听机制的特点: 1.事件源 2.事件 3.监听器 4.事件处理 事件源:就是awt包或者swing包中的那些图形用户界面组件.(如:按钮) 事件:每一个事件源都有自己特点有的对应事件和共性事件. ...
随机推荐
- 通过premake生成vs工程文件
visual studio的工程视图,在引用外部目录时非常麻烦,这时候可以使用premake一键生成工程文件,自动配置好工程的各种属性,还有目录的组织结构. 示例:如下是一个c++的外部目录结构,我们 ...
- Truck History POJ - 1789
题目链接:https://vjudge.net/problem/POJ-1789 思路: 题目意思就是说,给定一些长度为7的字符串,可以把字符串抽象为一个点, 每个点之间的距离就是他们本身字符串与其他 ...
- JS高阶---继承模式(原型链继承)
[前言] 之前已经介绍了对象创建的五种模式,下面看下继承模式 本节介绍下<原型链继承> [主体] 验证如下: 关键点: .
- 201871010112-梁丽珍《面向对象程序设计(java)》第十四周学习总结
项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p ...
- 201871020225-牟星源《面向对象程序设计(java)》第八周学习总结
201871020225-牟星源<面向对象程序设计(java)>第八周学习总结 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这 ...
- Shell编程 | 脚本参数与交互及常见问题
在执行一个脚本程序时,会经常需要向脚本传递一些参数,并根据输入的参数值生成相应的数据或执行特定的逻辑. 向脚本传递参数 执行Shell脚本时可以带有参数,在Shell脚本中有变量与之对应进行引用.这类 ...
- Windows解决端口占用问题
Windows解决端口占用问题 步骤 1. win + R,输入cmd回车进入dos界面 2. 输入netstat -ano|findstr 8080 查看占用8080端口的进程 3. 输入taskk ...
- onchange onpropertychange 和 oninput 事件的区别
onchange 事件在内容改变(两次内容有可能还是相等的)且失去焦点时触发. onpropertychange 事件却是实时触发,即每增加或删除一个字符就会触发,通过 js 改变也会触发该事件,但是 ...
- Mysql 时间和日期函数
参考文章 1 时间函数 当前日期和时间 select now(); 2 得到昨天的日期 CURDATE() 当前日期 select CURDATE()-1; -- curdate 3 添加时间间隔 当 ...
- 使用ES6 Class封装的IndexDB 操作类,并实现模糊搜索
封装如下: indexDBOperate.js export class IndexDBOperate { db = null // 数据库实例 databaseName = null // 数据库 ...