spring boot 监听容器启动代码实例
在使用Spring框架开发时, 有时我们需要在spring容器初始化完成后做一些操作, 那么我们可以通过自定义ApplicationListener 来实现.
自定义监听器
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// 获取spring 上下文
ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
// do your work...
}
源码分析
springboot 启动应用, 执行 SpringApplication.run(String… args) 方法
run方法中执行完初始化上下文方法后, 会执行this.refreshContext方法, 刷新
经过一堆方法跳转, 执行 AbstractApplicationContextl类的publishEvent(Object event, @Nullable ResolvableType eventType) 方法
然后执行 SimpleApplicationEventMulticaster.multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType)
然后依次执行所有监听器的onApplicationEvent()方法
// 遍历所有ApplicationListeners, 依次执行ApplicationListener 的onApplicationEvent()方法
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
Iterator var4 = this.getApplicationListeners(event, type).iterator();
while(var4.hasNext()) {
ApplicationListener<?> listener = (ApplicationListener)var4.next();
Executor executor = this.getTaskExecutor();
if (executor != null) {
executor.execute(() -> {
this.invokeListener(listener, event);
});
} else {
this.invokeListener(listener, event);
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Java基础开发之JDBC操作数据库增删改查,分页查询实例详解
这篇文章主要介绍了Java基础开发之JDBC操作数据库增删改查,分页查询实例详解,需要的朋友可以参考下2020-02-02
详解idea搭建springboot+mybatis框架的教程
这篇文章主要介绍了详解idea搭建springboot+mybatis框架的教程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-11-11
详解Lombok安装及Spring Boot集成Lombok
这篇文章主要介绍了详解Lombok安装及Spring Boot集成Lombok,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2019-03-03
IDEA 创建一个Mybatis Maven项目的方法步骤(图文)
这篇文章主要介绍了IDEA 创建一个Mybatis Maven项目的方法步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-03-03


最新评论