簡介
SpringBoot在如今開發過程用的很多,它爲我們的開發簡化了很多的配置,使我們可以輕而易舉完成大量複雜的開發任務。但是大多數人只是知其然而不知其所以然,因此本文章通過SpringBoot的啓動過程來深入的分一下SpringBoot底層是如何工作的。
啓動代碼
對於SpringBoot的啓動類,我們肯定都是非常的熟悉。具體代碼如下所示:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
源碼分析
通過啓動類DemoApplication(我們也一直是這麼做的),就可以完成Spring的初始化,自動裝配等一系列操作。本文通過兩個切入點:@SpringBootApplication和SpringApplication.run方法對啓動過程進行分析。
SpringApplication.run方法
首先,我們從run方法開始去看springboot內部是如何一步步的完成初始化工作的
(1)入口方法:在調用了靜態run方法後,通過一系列調用我們最終會進入到SpringAppliction類中如下位置:
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return (new SpringApplication(primarySources)).run(args);
}
可以看見,此方法完成了兩件工作,初始化SpringApplication類,並且調用內部的公有的run方法。接下來讓我們看看這兩步操作分別完成了哪些工作。
(2)SpringApplication初始化:主要代碼如下:
public SpringApplication(ResourceLoader resourceLoader, Class... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath(); #1
this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class)); #2
this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class)); #3
this.mainApplicationClass = this.deduceMainApplicationClass(); #4
}
上面的初始化代碼中,大部分是一些初始化工作,需要我們注意的是最後四行。接下來具體分析一下這四行做了什麼工作。
#1: 它的作用是通過類路徑的資源來判斷應用是屬於什麼類型。通過判斷代碼不難看出判斷思路如下:
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent("org.springframework.web.reactive.DispatcherHandler", (ClassLoader)null) && !ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", (ClassLoader)null) && !ClassUtils.isPresent("org.glassfish.jersey.servlet.ServletContainer", (ClassLoader)null)) {
return REACTIVE;
} else {
String[] var0 = SERVLET_INDICATOR_CLASSES;
int var1 = var0.length;
for(int var2 = 0; var2 < var1; ++var2) {
String className = var0[var2];
if (!ClassUtils.isPresent(className, (ClassLoader)null)) {
return NONE;
}
}
return SERVLET;
}
}
通過上面代碼不難看出判斷邏輯如下:
- 在類路徑中是否存在DispatcherHandler並且DispatcherServlet和ServletContainer都不存在。那麼自然就屬於REACTIVE類型的引用。不滿足則進行第二步
- 在類路徑中是否存在Servlet和ConfigurableWebApplicationContext,那麼就是Servlet應用
- 如果都不滿足則是普通的Java應用
#2: 主要是加載了已經註冊好的ApplicationContextInitializer實現類,並且將它實例化賦值給initializers,主要代碼如下所示:
加載註冊類
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = this.getClassLoader();
//加載註冊好的ApplicationContextInitializer實現類
Set<String> names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader)); #1
//將加載好的類進行實例化
List<T> instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names); #2
//根據優先級進行排序
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
實例化註冊類:根據上一步拿到的註冊類集合,進行實例化。
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) {
List<T> instances = new ArrayList(names.size());
Iterator var7 = names.iterator();
while(var7.hasNext()) {
String name = (String)var7.next();
try {
Class<?> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
T instance = BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
} catch (Throwable var12) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, var12);
}
}
return instances;
}
#4: 根據棧運行信息推測出運行主類
private Class<?> deduceMainApplicationClass() {
try {
//獲取運行時棧信息
StackTraceElement[] stackTrace = (new RuntimeException()).getStackTrace();
StackTraceElement[] var2 = stackTrace;
int var3 = stackTrace.length;
for(int var4 = 0; var4 < var3; ++var4) {
StackTraceElement stackTraceElement = var2[var4];
//判斷如果有main方法則代表是運行主類,獲取它的類名稱並且實例化。
if ("main".equals(stackTraceElement.getMethodName())) {
return Class.forName(stackTraceElement.getClassName());
}
}
} catch (ClassNotFoundException var6) {
;
}
return null;
}
總結:到這邊SpringApplication的初始化工作已經做完很容易發現,SpringBoot在這個步驟完成了一些標識符的初始化。並且根據註冊的信息初始化了ApplicationContextInitializer和ApplicationListener,推斷了應用的類型和運行主類。接下來我們看一看具體的run方法是如何完成容器的初始化的。
(3)run方法解析 :
run方法是具體進行Spring初始化的主體方法,讓我們來看看SpringBoot是如何引導這一切的發生的。
public ConfigurableApplicationContext run(String... args) {
#1 這一步SpringBoot會開啓一個監控器來監測並且計算應用開啓時間,充當一個監控器的角色
StopWatch stopWatch = new StopWatch();
stopWatch.start();
# 2 這邊是對一些必要的變量進行初始化
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
# 3 和上面初始化ApplicationListener類似,也是通過加載spring.factories預先配置的類對SpringApplicationRunListener進行實例化
SpringApplicationRunListeners listeners = getRunListeners(args);
# 4 開啓初始化好的監聽事件
listeners.starting();
try {
#5 封裝命令行參數
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
#6 準備參數環境 後續會專門寫文章進行詳細解析
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
#7 打印輸出
Banner printedBanner = printBanner(environment);
#8 創建Spring容器 對於Spring初始化週期也會後續會專門寫文章進行詳細解析
context = createApplicationContext();
#9 初始化SpringBoot 異常報告解析器
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
#10 初始化容器各項參數
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
#11 停止監控
stopWatch.stop();
#12 對啓動日誌進行封裝
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
#13 重新開啓一個事件來處理CommandLineRunner和ApplicationRunner
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
#14 在所有工作都完成後,重新發佈一個ApplicationReadyEvent事件表示Application已經準備完畢
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
補充
ApplicationContextInitializer初始化具體實現
#1: 加載spring.factories中已經註冊好的ApplicationContextInitializer的實現類的全路徑名稱,核心代碼如下:
主要步驟:
- 可以看見根據傳過來的類加載器,首先會在緩存map中查詢是否已經加載過,如果已經存在直接返回
- 不存在,那麼先去加載類路徑和系統路徑下的META-INF/spring.factories,獲取所有的spring.factories資源。
- 然後根據解析資源,將解析的類路徑名稱及其父類的映射關係存入LinkedMultiValueMap,最後將classLoader做爲key,將classLoader和LinkedMultiValueMap存入Map中。
- 最後根據factoryClassName,獲取需要的ApplicationContextInitializer的所有的實現類名稱集合
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
if (result != null) {
return result;
} else {
try {
Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
LinkedMultiValueMap result = new LinkedMultiValueMap();
while(urls.hasMoreElements()) {
URL url = (URL)urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
Iterator var6 = properties.entrySet().iterator();
while(var6.hasNext()) {
Entry<?, ?> entry = (Entry)var6.next();
String factoryClassName = ((String)entry.getKey()).trim();
String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
int var10 = var9.length;
for(int var11 = 0; var11 < var10; ++var11) {
String factoryName = var9[var11];
result.add(factoryClassName, factoryName.trim());
}
}
}
cache.put(classLoader, result);
return result;
} catch (IOException var13) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
}
}
}
#2和#3同理並且是獲取所有ApplicationListener的註冊類