SpringBoot(十五)启动流程分析最后阶段ApplicationStartedEvent、ApplicationReadyEvent事件发布、callRunners()

SpringBoot版本:2.1.1     ==》启动流程分析汇总

接上篇博客Spring Boot 2.1.1(十四)启动流程分析之refreshContext()

public ConfigurableApplicationContext run(String... args) {
            .... 
	try {
            //本篇内容从本行开始记录 
            //空实现 
            afterRefresh(context, applicationArguments);
			stopWatch.stop();
            //打印启动日志
	    if (this.logStartupInfo) {
	   	    new StartupInfoLogger(this.mainApplicationClass)
	   			    .logStarted(getApplicationLog(), stopWatch);
	    }
            //发布ApplicationStartedEvent事件
	    listeners.started(context); 
            //调用ApplicationRunner,CommandLineRunner的run方法
            callRunners(context, applicationArguments);         
            ....
        }
	catch (Throwable ex) {
		handleRunFailure(context, ex, exceptionReporters, listeners);
		throw new IllegalStateException(ex);
	}
        try {
                //发布ApplicationReadyEvent事件
		listeners.running(context);
	}
	catch (Throwable ex) {
		handleRunFailure(context, ex, exceptionReporters, null);
		throw new IllegalStateException(ex);
	}
    return context;
}

流程分析

1、afterRefresh()

空实现

 下面是启动日志输出

 2、发布ApplicationStartedEvent事件

两个listener,如下,啥也没做:

BackgroundPreinitializer

DelegatingApplicationListener

3、调用Runner

ApplicationRunner、CommandLineRunner这两个接口会在容器启动后进行调用,相当于开机启动,可以实现多个。

根据类型的到bean,根据order排序,循环调用接口的run()方法。

4、发布ApplicationReadyEvent事件

SpringApplicationAdminMXBeanRegistrar:ready改为true

BackgroundPreinitializer:参考这里

DelegatingApplicationListener:没执行什么

带一句ApplicationStartedEvent和ApplicationReadyEvent事件发布都是调用的AbstractApplicationContext的publishEvent()方法,可以看一下。不过该方法中最终发布事件还是调用的多播器EventMulticaster的multicastEvent()方法,也就是前面说过的事件发布方法。

完了完了,终于源码虐我千百遍,我待源码如初恋.........

 


版权声明:本文为yhahaha_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。