1、SpringBoot启动浅谈
2、SpringApplication.run(args)接口源码注释
public ConfigurableApplicationContext run(String... args) {
// 初始化
StopWatch stopWatch = new StopWatch(); // 构造一个任务执行观察器
stopWatch.start(); // 开始执行,记录开始时间
ConfigurableApplicationContext context = null;
configureHeadlessProperty();
// 获取SpringApplicationRunListeners,内部只有一个EventPublishingRunListener
SpringApplicationRunListeners listeners = getRunListeners(args);
// 上面分析过,会封装成SpringApplicationEvent事件然后广播出去给SpringApplication中的listeners所监听
// 这里接受ApplicationStartedEvent事件的listener会执行相应的操作
listeners.started();
try {
// 构造一个应用程序参数持有类
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
// 创建Spring容器
context = createAndRefreshContext(listeners, applicationArguments);
// 容器创建完成之后执行额外一些操作
afterRefresh(context, applicationArguments);
// 广播出ApplicationReadyEvent事件给相应的监听器执行
listeners.finished(context, null);
stopWatch.stop(); // 执行结束,记录执行时间
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, listeners, ex); // 这个过程报错的话会执行一些异常操作、然后广播出ApplicationFailedEvent事件给相应的监听器执行
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}