SpringBoot为何如此简单? 他到底做了什么? 让一个项目启动如此简单?这次我们简单看看spring为我们做了什么
以下是springboot项目启动方法
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
这里是关键核心代码
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
//1 统计埋点
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//2 默认启用Headless模式(Headless模式是在缺少显示屏、键盘或者鼠标时的系统配置)
configureHeadlessProperty();
//3 启动SpringApplicationRunListener 监听器
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
//4 配置运行环境
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//解析命令行参数
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
// 5 获取Banner
Banner printedBanner = printBanner(environment);
// 6 创建ApplicationContext
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
// 7 刷新IOC容器
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
// 8 发布ApplicationStartedEvent 事件
listeners.started(context);
// 9 启动所有ApplicationRunner 和 CommandLineRunner方法
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;
}
这是spring run 方法启动项目中所有执行的情况
主要总结为以下几个步骤
1 创建启动监听时间
2 启动SpringApplicationRunListener 监听器
3 解析并配置运行环境
4 创建IOC 容器,刷新IOC容器
5 启动所有 ApplicationRunner 和 CommandLineRunner