在上一篇中已经大致描述了Spring Boot的启动流程,这篇将根据源代码详细讲解SpringApplication类中的各种实现原理。通过run方法咱们首先会通过构造函数新建一个SpringApplication对象。咱们看下面代码看它具体做了什么。
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
//初始化资源加载器
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//初始化添加了@SpringBootApplication注解的class
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//应用类型
this.webApplicationType = deduceWebApplicationType();
//初始化ApplicationContextInitilizer,其中的原理是通过SpringFactoriesLoader来实现的
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
//初始化监听Application Listeners(2.0有好几个listener我没具体看过都是干嘛的所以不瞎写)
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//判断主类,主要作用是日志打印
this.mainApplicationClass = deduceMainApplicationClass();
}
接下来会调用初始化好的SpringApplication的run方法。
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
configureHeadlessProperty();//无关紧要,可以忽略
//Run Listeners 用于该函数中整个过程事件触发的监听EventPublishingRunListener用来调用构造器中初始化的几个listener
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
analyzers = new FailureAnalyzers(context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
其中下面两行代码
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
getRunlisteners方法也同样是通过SpringFactoriesLoader去获取spring.factories里面配置好的EventPublishingRunListener,该累的初始化的构造函数会传入SpringApplication,并将application中listener存储到retrievalMutex当中也可以叫defaultRetriever
之后调用该listerner中的starting方法代码如下
public void starting() {
this.initialMulticaster.multicastEvent(
new ApplicationStartingEvent(this.application, this.args));
}
通过新建的ApplicationStartingEvent去defaultRetriever中获取相对应event事件的listener执行对应的evet响应方法,并且会将defaultRetriever放入retrieverCache当中下次则可以直接通过evenType以及sourceType组成的key直接获取listener。到这SpringApplication的新建以及加载listener并运行listener启动都已经完成。到这咱们已经完成了第一章中的开始以及收集信息以及注册回调接口的阶段。下一章将细说创建并准备Environment。
加油!