SpringBoot启动篇
SpringBoot前期的准备工作
以前有过很无知的想法,为什么SpringBoot或者Tomcat启动后不会像其他main方法一样执行完毕就没了,而前两者能一直等着数据请求,其实SpringBoot也只是利用了内嵌Tomcat容器,而Tomcat容器设置了守护线程而已。
以下是整体概览
public ConfigurableApplicationContext run(String... args) {
//也只是执行了一些方法而已,传入的id为空
/* public StopWatch(String id) {
this.keepTaskList = true;
this.taskList = new LinkedList();
this.id = id;
} */
StopWatch stopWatch = new StopWatch();
//观察当前任务名是否不为空,不为空则说明已经启动,抛出如下错误
//Can't start StopWatch: it's already running
stopWatch.start();
//预先创建IOC容器
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
//设置无论有没有显示器都可以启动
this.configureHeadlessProperty();
// 探讨一:从spring.factories获取实现SpringApplicationRunListeners的类
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//广播启动程序启动通知
listeners.starting();
Collection exceptionReporters;
try {
//封装args参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//探讨二:准备环境变量,封装listener监听器,以及上述常见的实例
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
//忽略一些bean信息
this.configureIgnoreBeanInfo(environment);
//打印自定义Banner
Banner printedBanner = this.printBanner(environment);
//创建IOC容器
context = this.createApplicationContext();
//从spring.factories获取异常报告类,并封装到IOC容器context中
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//对ioc容器进行一些处理,将环境变量、监听器、应用参数、打印banner都封装到ioc中
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//这里是Spring的bean生命周期流程,暂时省略
//this.refreshContext(context);
//刷新容器之后对上下文进行一些处理
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);
}
}