public static void main(String[] args) {
SpringApplication.run(XXXApplication.class, args);
}
public ConfigurableApplicationContext run(String... args) {
// 记录程序运行时间
StopWatch stopWatch = new StopWatch();
stopWatch.start();
// 声明 ApplicationContext
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
// 设置 java.awt.headless 系统属性为 true - 没有图形化界面
this.configureHeadlessProperty();
// 第一步:获取并启动监听器
// 从 META-INF/spring.factories 中获取监听器
SpringApplicationRunListeners listeners = this.getRunListeners(args);
// 发布事件——“容器开始启动”
listeners.starting();
Collection exceptionReporters;
try {
// 第二步:构造 ApplicationContext 环境
// 配置计算机环境,Java 环境,Spring 运行环境,配置Spring 项目 Profiles(SpringBoot 的 application.properties/yml)等等。
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
// 处理需要忽略的 Bean
this.configureIgnoreBeanInfo(environment);
// 打印 banner
Banner printedBanner = this.printBanner(environment);
// 第三步:初始化 ApplicationContext
context = this.createApplicationContext();
// 准备异常报告器
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
// 第四步:ApplicationContext 的前置处理
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 第五步:刷新 ApplicationContext
// IoC 容器的初始化过程。
// 5.1 Resource 定位(包扫描)
// 5.2 BeanDefinition 的载入(加载 basePackage,判断 @Component 注解,存在即是 BeanDefinition)
// 5.3 注册 BeanDefinition(在 IoC 容器中将 BeanDefinition 注入到一个 ConcurrentHashMap 中)
this.refreshContext(context);
// 第六步:ApplicationContext 的后置处理
this.afterRefresh(context, applicationArguments);
// 时间记录停止
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
// 发布事件——“容器启动完成”
listeners.started(context);
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
listeners.running(context);
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}首先创建了 SpringApplication 的实例,然后调用了 SpringApplication 的 run() 方法。
SpringApplication.run() 方法
- 获取并启动监听器
- 构造 ApplicationContext 环境
- 初始化 ApplicationContext
- ApplicationContext 的前置处理
- 刷新 ApplicationContext(IoC 容器的初始化)
- ApplicationContext 的后置处理
版权声明:本文为weixin_35973945原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。