微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

spring boot 监听容器启动代码实例

这篇文章主要介绍了spring boot 监听容器启动代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

在使用Spring框架开发时, 有时我们需要在spring容器初始化完成后做一些操作, 那么我们可以通过自定义ApplicationListener 来实现.

自定义监听器

@Component public class MyApplicationListener implements ApplicationListener { @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); } } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐