Spring Boot是一个基于Spring框架的快速开发工具,它可以帮助我们快速搭建一个可运行的Spring应用。本文将详细介绍Spring Boot的启动流程,帮助大家更好地理解Spring Boot的工作原理。
一、Spring Boot启动流程概述
Spring Boot的启动流程可以分为以下几个阶段:
-
初始化配置
-
创建应用程序上下文
-
刷新上下文(启动核心)
-
通知监听者-启动程序完成
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);
// 读取Springboot配置文件并创建Environment对象
// 这里创建的Environment对象实际为ConfigurableEnvironment
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, bootstrapContext, applicationArguments);
this.configureIgnoreBeanInfo(environment);
// 打印Banner图标
Banner printedBanner = this.printBanner(environment);
// 创建ApplicationContext应用行下文,即创建容器
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);
}
// 调用运行时监听器的started()方法
// 该方法需要在应用程序启动后,CommandLineRunners和ApplicationRunners被调用前执行
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