spring boot 监听容器启动代码实例
2019-10-16 18:07
831 查看
在使用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); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- Spring boot + LayIM + t-io 实现文件上传、 监听用户状态的实例代码
- SpringBoot Tomcat启动实例代码详解
- springboot集成mybatis实例代码
- SpringBoot与Quartz集成实现分布式定时任务集群的代码实例
- springboot项目中使用mybatis逆向工程生成代码实例
- spring boot + mybatis实现动态切换数据源实例代码
- Spring boot设置启动监听端口
- spring boot容器启动详解
- SpringBoot创建JSP登录页面功能实例代码
- spring boot springjpa 支持多个数据源的实例代码
- IDEA启动多个Spring Boot工程实例
- SpringBoot从Eclipse添加的Tomcat容器中启动
- springBoot 设置服务启动时执行代码
- 如何在IDEA启动多个Spring Boot工程实例
- Spring Boot定时任务的使用实例代码
- Spring Boot 启动配置原理和启动事件监听
- 监听Spring Boot的启动、停止、重启、关闭
- SpringBoot中嵌入式Servlet容器启动原理;
- Spring-boot原理(附带实现一个spring-boot-starter实例和代码下载)
- SpringBoot+MyBatis简单数据访问应用的实例代码