srpingboot web - 启动(3) 监听器(spring boot是干嘛的)

网友投稿 249 2022-08-04

srpingboot web - 启动(3) 监听器(spring boot是干嘛的)

一. 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

1. 这里创建了一个多播器: SimpleApplicationEventMulticaster

2. 将容器中10个监听器放入多播器中.

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

这里的顺序与配置的读取顺序不同, 是经过排序过的.

addApplicationListener()

ListenerRetriever 是 AbstractApplicationEventMulticaster 的一个内部类. 所以监听器是放在 一个内部类的 applicationListeners 属性中:

public final Set> applicationListeners;

二. listeners.starting()

public void starting() {

for (SpringApplicationRunListener listener : this.listeners) {

listener.starting();

}

}

此处的 this.listeners 中的 this -> SpringApplicationRunListeners .

所以调用的是 EventPublishingRunListener的starting() 方法.

看一下 multicastEvent 方法:

getApplicationListeners()

1.  判断监听器是否为 GenericApplicationListener 类型

|-> 如果是, 则调用其 supportsEventType() 和 supportsSourceType() , 且同时满足, 才可以. 否则会被过滤掉

|-> 如果不是, 则 使用GenericApplicationListenerAdapter 进行适配转换, 然后 调用上面两个方法, 同时满足, 才可以. 否则会被过滤掉

满足条件的有4个监听器:

此处看一下 LoggingApplicationListener 的两个方法执行:

1. supportsEventType()

可以看到, 这里他支持5中类型, 其中正好就有当前发布的 ApplicationStartingEvent 事件.

2. supportsSourceType()

invokeListener()

这里就是调用 监听器的  onApplicationEvent 方法, 并传入要多波的事件.

这里仍然来看 LoggingApplicationListener 的 onApplicationEvent 方法:

不同的事件进来, 执行不同的方法.

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot web - 启动(2) run()
下一篇:同一服务器下发布两个不同网站(war包)的方法(这里采用的是二级域名的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~