srpingboot web - 启动(3) 监听器
接上一篇
一. getRunListeners()
在run() 方法中调用了 getRunListeners(args) 方法, 先看一下这个方法干了什么
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(
SpringApplicationRunListener.class, types, this, args));
}
加载配置 spring.factories 中的配置,
# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener
然后创建配置中的 EventPublishingRunListener , 封装到 SpringApplicationRunListeners 类中的 this.listeners 属性中.
1. 创建 EventPublishingRunListener
public EventPublishingRunListener(SpringApplication application, String[] args) {
this.application = application;
this.args = args;
this.initialMulticaster = new SimpleApplicationEventMulticaster();
for (ApplicationListener<?> listener : application.getListeners()) {
this.initialMulticaster.addApplicationListener(listener);
}
}
1. 这里创建了一个多播器: SimpleApplicationEventMulticaster

2. 将容器中10个监听器放入多播器中.
上一篇提到过, 容器中加载了10个监听器, 放在 this.listeners 属性中.

这里的顺序与配置的读取顺序不同, 是经过排序过的.
addApplicationListener()
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
synchronized (this.retrievalMutex) {
// Explicitly remove target for a proxy, if registered already,
// in order to avoid double invocations of the same listener.
Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
if (singletonTarget instanceof ApplicationListener) {
this.defaultRetriever.applicationListeners.remove(singletonTarget);
}
this.defaultRetriever.applicationListeners.add(listener);
this.retrieverCache.clear();
}
}
ListenerRetriever 是 AbstractApplicationEventMulticaster 的一个内部类. 所以监听器是放在 一个内部类的 applicationListeners 属性中:
public final Set<ApplicationListener<?>> applicationListeners;
二. listeners.starting()
public void starting() {
for (SpringApplicationRunListener listener : this.listeners) {
listener.starting();
}
}
此处的 this.listeners 中的 this -> SpringApplicationRunListeners .
所以调用的是 EventPublishingRunListener的starting() 方法.
//EventPublishingRunListener.java
@Override
public void starting() {
//创建Application的启动事件, 并进行多波
this.initialMulticaster.multicastEvent(
new ApplicationStartingEvent(this.application, this.args));
}
看一下 multicastEvent 方法:
//SimpleApplicationEventMulticaster.java
@Override
public void multicastEvent(ApplicationEvent event) {
multicastEvent(event, resolveDefaultEventType(event));
} @Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
// getApplicationListeners 会对监听器进行过滤
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
//获取线程池, 暂时为null
Executor executor = getTaskExecutor();
if (executor != null) {
//异步发送事件
executor.execute(() -> invokeListener(listener, event));
}
else {
//同步发送事件
invokeListener(listener, event);
}
}
}
getApplicationListeners()
protected boolean supportsEvent(
ApplicationListener<?> listener, ResolvableType eventType, @Nullable Class<?> sourceType) { GenericApplicationListener smartListener = (listener instanceof GenericApplicationListener ?
(GenericApplicationListener) listener : new GenericApplicationListenerAdapter(listener));
return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType));
}
1. 判断监听器是否为 GenericApplicationListener 类型
|-> 如果是, 则调用其 supportsEventType() 和 supportsSourceType() , 且同时满足, 才可以. 否则会被过滤掉
|-> 如果不是, 则 使用GenericApplicationListenerAdapter 进行适配转换, 然后 调用上面两个方法, 同时满足, 才可以. 否则会被过滤掉
满足条件的有4个监听器:

此处看一下 LoggingApplicationListener 的两个方法执行:
1. supportsEventType()
private static final Class<?>[] EVENT_TYPES = { ApplicationStartingEvent.class,
ApplicationEnvironmentPreparedEvent.class, ApplicationPreparedEvent.class,
ContextClosedEvent.class, ApplicationFailedEvent.class };
@Override
public boolean supportsEventType(ResolvableType resolvableType) {
return isAssignableFrom(resolvableType.getRawClass(), EVENT_TYPES);
}
@Override
public boolean supportsSourceType(Class<?> sourceType) {
return isAssignableFrom(sourceType, SOURCE_TYPES);
}
private boolean isAssignableFrom(Class<?> type, Class<?>... supportedTypes) {
if (type != null) {
for (Class<?> supportedType : supportedTypes) {
if (supportedType.isAssignableFrom(type)) {
return true;
}
}
}
return false;
}
可以看到, 这里他支持5中类型, 其中正好就有当前发布的 ApplicationStartingEvent 事件.
2. supportsSourceType()
private static final Class<?>[] SOURCE_TYPES = { SpringApplication.class,
ApplicationContext.class };
@Override
public boolean supportsSourceType(Class<?> sourceType) {
//这里调用的还是上面的那个方法, 只是传入参数不同
return isAssignableFrom(sourceType, SOURCE_TYPES);
}
invokeListener()
protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
//不管 errorhandler 是否为null, 都会调用 doInvokeListener 方法
ErrorHandler errorHandler = getErrorHandler();
if (errorHandler != null) {
try {
doInvokeListener(listener, event);
}
catch (Throwable err) {
errorHandler.handleError(err);
}
}
else {
doInvokeListener(listener, event);
}
}
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass().getName())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception and just log a debug message.
Log logger = LogFactory.getLog(getClass());
if (logger.isDebugEnabled()) {
logger.debug("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
这里就是调用 监听器的 onApplicationEvent 方法, 并传入要多波的事件.
这里仍然来看 LoggingApplicationListener 的 onApplicationEvent 方法:
@Override
public void onApplicationEvent(ApplicationEvent event) {
//Application启动
if (event instanceof ApplicationStartingEvent) {
onApplicationStartingEvent((ApplicationStartingEvent) event);
}
//环境准备完成
else if (event instanceof ApplicationEnvironmentPreparedEvent) {
onApplicationEnvironmentPreparedEvent(
(ApplicationEnvironmentPreparedEvent) event);
}
//Application 准备完
else if (event instanceof ApplicationPreparedEvent) {
onApplicationPreparedEvent((ApplicationPreparedEvent) event);
}
//容器关闭
else if (event instanceof ContextClosedEvent && ((ContextClosedEvent) event)
.getApplicationContext().getParent() == null) {
onContextClosedEvent();
}
//Application启动失败
else if (event instanceof ApplicationFailedEvent) {
onApplicationFailedEvent();
}
}
不同的事件进来, 执行不同的方法.
srpingboot web - 启动(3) 监听器的更多相关文章
- springboot web - 启动(2) run()
接上一篇 在创建 SpringApplication 之后, 调用了 run() 方法. public ConfigurableApplicationContext run(String... arg ...
- WEB启动时就加载servlet的dopost方法
web启动的时候可以加载servlet的init方法,无法加载dopost方法,如果你需要什么内容在启动的时候执行,可以将内容放到init方法里面,dopost方法,是在客户端使用post请求的时候才 ...
- 从web启动winform程序
最近有个客户提出想从网站上启动一个客户端的程序,研究了下,实现方法如下: 1. 注入注册表 try { string appPath ...
- Jenkins新建节点,启动方式没有“通过Java Web启动代理”选项怎么办?
在Jenkins中,打开“系统管理”→“管理节点”→“新建节点”页面时,“启动方式”选项没有“通过Java Web启动代理”,怎么办? 打开“系统管理”,进入“全局安全配置”页面. 1. “JNLP代 ...
- Jenkins新建节点找不到通过Java web启动代理?
参考博客:Jenkins新建节点,启动方式没有“通过Java Web启动代理”选项怎么办? 在Jenkins中,打开“系统管理”→“管理节点”→“新建节点”页面时,“启动方式”选项没有“通过Java ...
- 启动oracle11监听器错误
启动oracle11监听器错误:本地计算机上的OracleOraDb11g_home1TNSListener服务启动后又停止了解决方案 . 关键字:启动oracle10监听器错误:本地计算机上的Ora ...
- 启动web项目,监听器、过滤器、拦截器启动顺序
启动顺序:监听器 > 过滤器 > 拦截器 记忆技巧:接到命令,监听电报,过滤敌情,拦截行动.
- web.xml中监听器配置
<!-- 监听器的配置:监听器配置完以后,应用系统在启动的时候就会开启这些监听器. 监听器的理解:监听器好比一个卫兵,卫兵一直站在那里等待长官的命令,当卫兵收到长官的命令以后,立即执行 之前已经 ...
- Web中的监听器【Listener】
Servlet监听器:Servlet规范中定义的一种特殊类,它用于监听Web应用程序中的ServletContext.HttpSession和ServletRequest等域对象的创建与销毁事件,以及 ...
随机推荐
- 最大连续和(dp复习)
最大连续和:给出一段序列,选出其中连续且非空的一段使得这段和最大. stdin: 7 2 -4 3 -1 2 -4 3 stdout: 4 状态转移方程:dp[i]=max(dp[i-1]+a[i], ...
- pandas行列显示不全的问题
https://blog.csdn.net/rookie_is_me/article/details/83991490
- LaTeX技巧472:定义一个LaTeX参考文献不带编号且有缩进的方法
LaTeX_Fun的博客 LaTeX技巧381:参考文献项第二行缩进如何定义? \makeatletter\renewenvironment{thebibliography}[1]{\section* ...
- CCF_ 201403-3 _命令行选项
不要怀疑,这题跟CCF_201604-3_路径解析一样恶心,很多中情况,要仔细读题,注意细节. 写的比较乱. #include<iostream> #include<cstdio&g ...
- Codeforces 1087C Connect Three (思维+模拟)
题意: 网格图选中三个格,让你选中一些格子把这三个格子连起来,使得选中的格子总数最小.最后输出方案 网格范围为1000 思路: 首先两点间连起来最少需要的格子为他们的曼哈顿距离 然后连接方案一定是曼哈 ...
- 第2章 Java并行程序基础(二)
2.3 volatile 与 Java 内存模型(JMM) volatile对于保证操作的原子性是由非常大的帮助的(可见性).但是需要注意的是,volatile并不能代替锁,它也无法保证一些复合操作的 ...
- PHP5.3的VC9、VC6、Thread Safe、Non Thread Safe的区别
PHP一共给了四个版本,VC9 x86 Non Thread Safe.VC9 x86 Thread Safe.VC6 x86 Non Thread Safe.VC6 x86 Thread Safe, ...
- Hexo搭建静态博客踩坑日记(一)
前言 博客折腾一次就好, 找一个适合自己的博客平台, 专注于内容进行提升. 方式一: 自己买服务器, 域名, 写前端, 后端(前后分离最折腾, 不分离还好一点)... 方式二: 利用Hexo, Hug ...
- ELF文件之五——使用链接脚本-2个函数-data-bss
main.c int enable; ; int main() { ; } int add() { ; } bss段在elf中虽然size是4,但并不占filesize,节头表如下图所示 程序头中,项 ...
- Java基础环境配置及HelloWorld
一.什么是JDK,JRE JDK(Java Development Kit Java开发工具包) JDK是提供给Java开发人员使用的,其中包含了java的开发工具,也包括了JRE.所以安装了JDK, ...