SpringBoot應(yīng)用啟動(dòng)流程源碼解析
前言
Springboot應(yīng)用在啟動(dòng)的時(shí)候分為兩步:首先生成 SpringApplication 對(duì)象 ,運(yùn)行 SpringApplication 的 run 方法,下面一一看一下每一步具體都干了什么
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
創(chuàng)建 SpringApplication 對(duì)象
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//保存主配置類
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//判斷當(dāng)前是否一個(gè)web應(yīng)用
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//從類路徑下找到META-INF/spring.factories配置的所有ApplicationContextInitializer;然后保存起來(lái)
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//從類路徑下找到ETA-INF/spring.factories配置的所有ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//從多個(gè)配置類中找到有main方法的主配置類
this.mainApplicationClass = deduceMainApplicationClass();
}
其中從類路徑下獲取到META-INF/spring.factories配置的所有ApplicationContextInitializer和ApplicationListener的具體代碼如下
public final class SpringFactoriesLoader {
/**spring.factories的位置*/
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);
/**
* 緩存掃描后的結(jié)果, 注意這個(gè)cache是static修飾的,說(shuō)明是多個(gè)實(shí)例共享的
* 其中MultiValueMap的key就是spring.factories中的key(比如org.springframework.boot.autoconfigure.EnableAutoConfiguration),
* 其值就是key對(duì)應(yīng)的value以逗號(hào)分隔后得到的List集合(這里用到了MultiValueMap,他是guava的一鍵多值map, 類似Map<String, List<String>>)
*/
private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();
private SpringFactoriesLoader() {
}
/**
* AutoConfigurationImportSelector及應(yīng)用的初始化器和監(jiān)聽(tīng)器里最終調(diào)用的就是這個(gè)方法,
* 這里的factoryType是EnableAutoConfiguration.class、ApplicationContextInitializer.class、或ApplicationListener.class
* classLoader是AutoConfigurationImportSelector、ApplicationContextInitializer、或ApplicationListener里的beanClassLoader
*/
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
String factoryTypeName = factoryType.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}
/**
* 加載 spring.factories文件的核心實(shí)現(xiàn)
*/
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
// 先從緩存獲取,如果獲取到了說(shuō)明之前已經(jīng)被加載過(guò)
MultiValueMap<String, String> result = cache.get(classLoader);
if (result != null) {
return result;
}
try {
// 找到所有jar中的spring.factories文件的地址
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
// 循環(huán)處理每一個(gè)spring.factories文件
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
// 加載spring.factories文件中的內(nèi)容到Properties對(duì)象中
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
// 遍歷spring.factories內(nèi)容中的所有的鍵值對(duì)
for (Map.Entry<?, ?> entry : properties.entrySet()) {
// 獲得spring.factories內(nèi)容中的key(比如org.springframework.boot.autoconfigure.EnableAutoConfiguratio)
String factoryTypeName = ((String) entry.getKey()).trim();
// 獲取value, 然后按英文逗號(hào)(,)分割得到value數(shù)組并遍歷
for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
// 存儲(chǔ)結(jié)果到上面的多值Map中(MultiValueMap<String, String>)
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
}
運(yùn)行run方法
public ConfigurableApplicationContext run(String... args) {
//開(kāi)始停止的監(jiān)聽(tīng)
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//聲明一個(gè)可配置的ioc容器
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
//配置awt相關(guān)的東西
configureHeadlessProperty();
//獲取SpringApplicationRunListeners;從類路徑下META-INF/spring.factories
SpringApplicationRunListeners listeners = getRunListeners(args);
//回調(diào)所有的獲取SpringApplicationRunListener.starting()方法
listeners.starting();
try {
//封裝命令行參數(shù)
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//準(zhǔn)備環(huán)境
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
//創(chuàng)建環(huán)境完成后回調(diào)SpringApplicationRunListener.environmentPrepared();表示環(huán)境準(zhǔn)備完成
Banner printedBanner = printBanner(environment);
//創(chuàng)建ApplicationContext;決定創(chuàng)建web的ioc還是普通的ioc,
//通過(guò)反射創(chuàng)建ioc容器((ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);)
context = createApplicationContext();
//出現(xiàn)異常之后做異常分析報(bào)告
analyzers = new FailureAnalyzers(context);
//準(zhǔn)備上下文環(huán)境;將environment保存到ioc中;而且applyInitializers();
//applyInitializers():回調(diào)之前保存的所有的ApplicationContextInitializer的initialize方法
//回調(diào)所有的SpringApplicationRunListener的contextPrepared();
//
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//prepareContext運(yùn)行完成以后回調(diào)所有的SpringApplicationRunListener的contextLoaded();
//刷新容器;ioc容器初始化(如果是web應(yīng)用還會(huì)創(chuàng)建嵌入式的Tomcat);Spring注解版
//掃描,創(chuàng)建,加載所有組件的地方;(配置類,組件,自動(dòng)配置)
refreshContext(context);
//從ioc容器中獲取所有的ApplicationRunner和CommandLineRunner進(jìn)行回調(diào)
//ApplicationRunner先回調(diào),CommandLineRunner再回調(diào)
afterRefresh(context, applicationArguments);
//所有的SpringApplicationRunListener回調(diào)finished方法
listeners.finished(context, null);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
//整個(gè)SpringBoot應(yīng)用啟動(dòng)完成以后返回啟動(dòng)的ioc容器;
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
幾個(gè)重要的事件回調(diào)機(jī)制
配置在META-INF/spring.factories
ApplicationContextInitializer
SpringApplicationRunListener
只需要放在ioc容器中
ApplicationRunner
CommandLineRunner
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java向es中寫入數(shù)據(jù)報(bào)錯(cuò)org.elasticsearch.action.ActionReque問(wèn)題
這篇文章主要介紹了java向es中寫入數(shù)據(jù)報(bào)錯(cuò)org.elasticsearch.action.ActionReque問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
使用Java8進(jìn)行分組(多個(gè)字段的組合分組)
本文主要介紹了使用Java8進(jìn)行分組(多個(gè)字段的組合分組),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
SpringBoot整合EasyExcel實(shí)現(xiàn)Excel表格導(dǎo)出功能
這篇文章主要介紹了SpringBoot整合EasyExcel實(shí)現(xiàn)Excel表格導(dǎo)出功能,文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-07-07
Spring與Mybatis相結(jié)合實(shí)現(xiàn)多數(shù)據(jù)源切換功能
這篇文章主要介紹了Spring與Mybatis相結(jié)合實(shí)現(xiàn)多數(shù)據(jù)源切換功能的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06
sentinel配置 持久化到nacos的詳細(xì)過(guò)程
這篇文章主要介紹了sentinel配置 持久化到nacos的詳細(xì)過(guò)程,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧2024-08-08
解決java.lang.ClassCastException的java類型轉(zhuǎn)換異常的問(wèn)題
這篇文章主要介紹了解決java.lang.ClassCastException的java類型轉(zhuǎn)換異常的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
springMVC自定義注解,用AOP來(lái)實(shí)現(xiàn)日志記錄的方法
下面小編就為大家分享一篇springMVC自定義注解,用AOP來(lái)實(shí)現(xiàn)日志記錄的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01

