Spring 5底层原理 系列的学习笔记
SpringApplication#run(java.lang.String...)
源码
public ConfigurableApplicationContext run(String... args) {
long startTime = System.nanoTime();
DefaultBootstrapContext bootstrapContext = this.createBootstrapContext();
ConfigurableApplicationContext context = null;
this.configureHeadlessProperty();
// 获取事件分发器
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
// 封装启动 args
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//Environment 即环境对象,是对配置信息的抽象,配置信息的来源有多种,比如:
// 系统环境变量、properties 配置文件、YAML 配置文件等等。
// SpringBoot 提供了名为 ApplicationEnvironment 的类表示环境对象,
// 它是 Spring 中 StandardEnvironment 环境对象的子类。
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);
this.configureIgnoreBeanInfo(environment);
// 打印banner
Banner printedBanner = this.printBanner(environment);
context = this.createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
this.prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
// 刷新容器
this.refreshContext(context);
// 刷新后置处理
this.afterRefresh(context, applicationArguments);
Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), timeTakenToStartup);
}
listeners.started(context, timeTakenToStartup);
this.callRunners(context, applicationArguments);
} catch (Throwable var12) {
this.handleRunFailure(context, var12, listeners);
throw new IllegalStateException(var12);
}
try {
Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
listeners.ready(context, timeTakenToReady);
return context;
} catch (Throwable var11) {
this.handleRunFailure(context, var11, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var11);
}
}
总结
发布 Application Starting 事件 1??
发布 Application Environment 已准备事件 2??
application.properties 由 StandardConfigDataLocationResolver 解析
spring.application.json
发布 Application Context 已初始化事件 3??
发布 Application Prepared 事件 4??
发布 Application Started 事件 5??
发布 Application Ready 事件 6??
这其中有异常,发布 Application Failed 事件 7??