使用spring Boot已经快1年多了,期间一直想点开springboot源码查看,但由于种种原因一直未能如愿(主要是人类的惰性。。。),今天就拿springboot 的监听事件祭刀。

springboot 中常用的事件监听主要有ApplicationStartedEvent,ApplicationEnviromentPreparedEvent,ApplicationPreparedEvent,ApplicationStoppedEvent等。用于监听springboot生命周期中的各种事件。

说到监听都会不由自主想到观察者模式,springboot的事件监听实现也没出意外,它的实现机制也是一个典型的观察者模式,只不过稍微复杂点罢了。springboot将观察者放入一个list中委托

SimpleApplicationEventMulticaster管理。这里有个有意思的地方,srpingboot在实例化SpringApplicationRunListener 时并没有通过正常的途径(比如new,或者其他实例化方法),而是将接口的实现类交由

SpringFactoriesLoader去 META-INF/spring.factories 下装载:

public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
try {
Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
List<String> result = new ArrayList<String>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
String factoryClassNames = properties.getProperty(factoryClassName);
result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
}
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}

这里通过classLoader的getResources方法将所有的META-INF/spring.factories资源都装载进来。

springboot为什么要不惜花费这么大代价去装载一个接口的实现呢,稍微分析一下还是很清晰的,首先,将接口和实现分离,这是典型的依赖注入,如果从单个应用程序来看,大不必这样。关键就在SpringFactoriesLoader里,如上所说,SpringFactoriesLoader是将所有的配置都装载进来,也就是说springboot在为以后的扩展留了条后路,当有新的jar包(意味着又升级啦)加进来,并且需要添加新的的监听事件类型时,就不用修改原有的代码。这就是传说中的对修改关闭对扩展开放的典型例子。

接着说,那么SpringFactoriesLoader装载的实例到底是什么呢, EventPublishingRunListener!

这货也就是个中间类,承接了事件的管理和事件的广播,正真的主角是SimpleApplicationEventMulticaster类,该类的实例在EventPublishingRunListener实例化时被创建出来。

里面有个ListenerRetriever内部类,这个类有两个作用,一个default,SimpleApplicationEventMulticaster初始化时被创建,含有所有的观察者,并作为各种操作的同步锁,还有就是将观察者分类,分类的依据有两个,

一个是事件类型eventType,还有一个是事件原始对象类型sourceType,sourceType是每个事件都会有的,这里是applicationContext。,分类好后,会在事件发生时由最上层SpringApplication发起通知,最后由SimpleApplicationEventMulticaster对象分别调用每个具体的观察者:

protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
listener.onApplicationEvent(event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || msg.startsWith(event.getClass().getName())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
Log logger = LogFactory.getLog(getClass());
if (logger.isDebugEnabled()) {
logger.debug("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
}

至此,一个完整的从事件注册到事件出发再到事件执行完毕的流程结束。山路十八弯,沿途风景多,细细品味还是会有一番收获的。这当中仍有许多细节未能一一道出,比如hashmap的hashCode的重写分析,比如同步锁的使用原因等等。

转载请注明出处。

spring boot 源码赏析之事件监听的更多相关文章

  1. (转)spring boot实战(第三篇)事件监听源码分析

    原文:http://blog.csdn.net/liaokailin/article/details/48194777 监听源码分析 首先是我们自定义的main方法: package com.lkl. ...

  2. Spring Boot源码分析-配置文件加载原理

    在Spring Boot源码分析-启动过程中我们进行了启动源码的分析,大致了解了整个Spring Boot的启动过程,具体细节这里不再赘述,感兴趣的同学可以自行阅读.今天让我们继续阅读源码,了解配置文 ...

  3. Spring Boot源码分析-启动过程

    Spring Boot作为目前最流行的Java开发框架,秉承"约定优于配置"原则,大大简化了Spring MVC繁琐的XML文件配置,基本实现零配置启动项目. 本文基于Spring ...

  4. 曹工说Spring Boot源码(21)-- 为了让大家理解Spring Aop利器ProxyFactory,我已经拼了

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

  5. 精尽Spring Boot源码分析 - SpringApplication 启动类的启动过程

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  6. 精尽Spring Boot源码分析 - 支持外部 Tomcat 容器的实现

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  7. 精尽Spring Boot源码分析 - 配置加载

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  8. 精尽Spring Boot源码分析 - 日志系统

    该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...

  9. Spring Boot源码中模块详解

    Spring Boot源码中模块详解 一.源码 spring boot2.1版本源码地址:https://github.com/spring-projects/spring-boot/tree/2.1 ...

随机推荐

  1. preload & prefetch

    原文地址在 我的笔记里,觉得还行就给个 star 吧:) 关于 preload 和 prefetch 早有耳闻,知道它们可以优化页面加载速度,然具体情况却了解不多.搜索了相关的资料后对其有了些认识,在 ...

  2. ionic监听android返回键(实现“再按一次退出”功能)

    在android平台上的app,在主页面时经常会遇到"再按一次退出app"的功能,避免只按一下返回键就退出app提升体验优化. 1.这个功能需要我们用到ionic提供的regist ...

  3. Python 存储数据到json文件

    1 前言 很多程序都要求用户输入某种信息,程序一般将信息存储在列表和字典等数据结构中. 用户关闭程序时,就需要将信息进行保存,一种简单的方式是使用模块json来存储数据. 模块json让你能够将简单的 ...

  4. 关于在layui中的table checkbox 默认选中设置

    一.layui版本 layui-v2.4.5 二.设置table的checkbox默认选中 总共有两种方法: 方法1:在返回的json中设置LAY_CHECKED为true,页面上的checkbox就 ...

  5. 第二章、 Vue 起步

    2-2.编写hello world 首先创建vue实例,然后实例接收一些配置项,el表示实例负责管理的区域,data表示区域内的数据 两秒后内容变为bye world 其中app表示实例对象,$dat ...

  6. vue中eslint报错的解决方案

    1,Newline required at end of file but not found. (eol-last) //文末需要一行 这个是报错: 这个是不报错的: 只需要在最后一行加上一空行即可 ...

  7. hibernate中cascade属性以及inverse属性

    级联操作 cascadecascade的常用属性值 none 默认值 不做任何变动 save-update 保存或修改 delete 删除 all 包含save-update 和delete等行为 c ...

  8. 三星最先进EUV产线投用

    近日,三星宣布,在韩国华城工业园新开一条专司 EUV(极紫外光刻)技术的晶圆代工产线 V1,最次量产 7nm. 据悉,V1 产线/工厂 2018 年 2 月动工,2019 年下半年开始测试晶圆生产,首 ...

  9. C++ 在界面中添加图片

    #include <stdio.h> #include <easyx.h> #include <graphics.h> void huayuan() { Begin ...

  10. 关于beforeRouteEnter中的next()

    beforeRouteEnter(to,from, next){ console.log(this)   //undefined next(vm => { console.log(vm)}) } ...