经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
spring boot 监听容器启动代码实例
来源:jb51  时间:2019/10/17 9:04:42  对本文有异议

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

自定义监听器

  1. @Component
  2. public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
  3.  
  4. @Override
  5. public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
  6.  
  7. // 获取spring 上下文
  8. ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
  9.  
  10. // do your work...
  11. }

源码分析

springboot 启动应用, 执行 SpringApplication.run(String… args) 方法

run方法中执行完初始化上下文方法后, 会执行this.refreshContext方法, 刷新

经过一堆方法跳转, 执行 AbstractApplicationContextl类的publishEvent(Object event, @Nullable ResolvableType eventType) 方法

然后执行 SimpleApplicationEventMulticaster.multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType)

然后依次执行所有监听器的onApplicationEvent()方法

  1. // 遍历所有ApplicationListeners, 依次执行ApplicationListener 的onApplicationEvent()方法
  2. public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
  3. ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
  4. Iterator var4 = this.getApplicationListeners(event, type).iterator();
  5.  
  6. while(var4.hasNext()) {
  7. ApplicationListener<?> listener = (ApplicationListener)var4.next();
  8. Executor executor = this.getTaskExecutor();
  9. if (executor != null) {
  10. executor.execute(() -> {
  11. this.invokeListener(listener, event);
  12. });
  13. } else {
  14. this.invokeListener(listener, event);
  15. }
  16. }
  17.  
  18. }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号