javascript
SpringBoot2.x启动原理概述
Spring Boot 的入口類
@SpringBootApplication public class SpringBootBestPracticeApplication {public static void main(String[] args) {SpringApplication.run(SpringBootBestPracticeApplication.class, args);} }做過 Spring Boot 項目的都知道,上面是 Spring Boot 最簡單通用的入口類。入口類的要求是最頂層包下面第一個含有 main 方法的類,使用注解 @SpringBootApplication 來啟用 Spring Boot 特性,使用 SpringApplication.run 方法來啟動 Spring Boot 項目。
來看一下這個類的run方法調用關系源碼:
public static ConfigurableApplicationContext run( Class<?> primarySource,String... args) {return run(new Class<?>[] { primarySource }, args); } public static ConfigurableApplicationContext run(Class<?>[] primarySources,String[] args) {return new SpringApplication(primarySources).run(args); }第一個參數primarySource:加載的主要資源類
第二個參數 args:傳遞給應用的應用參數
先用主要資源類來實例化一個 SpringApplication 對象,再調用這個對象的 run 方法,所以我們分兩步來分析這個啟動源碼。
SpringApplication 的實例化過程
接著上面的?SpringApplication?構造方法進入以下源碼:
public SpringApplication(Class<?>... primarySources) {this(null, primarySources); }public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {// 1、資源初始化資源加載器為 nullthis.resourceLoader = resourceLoader;// 2、斷言主要加載資源類不能為 null,否則報錯Assert.notNull(primarySources, "PrimarySources must not be null");// 3、初始化主要加載資源類集合并去重this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));// 4、推斷當前 WEB 應用類型this.webApplicationType = deduceWebApplicationType();// 5、設置應用上線文初始化器setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); // 6、設置監聽器setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));// 7、推斷主入口應用類this.mainApplicationClass = deduceMainApplicationClass();}可知這個構造器類的初始化包括以下 7 個過程。
1. 資源初始化資源加載器為 null
2. 斷言主要加載資源類不能為 null,否則報錯
Assert.notNull(primarySources, "PrimarySources must not be null");3. 初始化主要加載資源類集合并去重
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));4. 推斷當前 WEB 應用類型
this.webApplicationType = deduceWebApplicationType();來看下?deduceWebApplicationType?方法和相關的源碼:
private WebApplicationType deduceWebApplicationType() {if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)&& !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {return WebApplicationType.REACTIVE;}for (String className : WEB_ENVIRONMENT_CLASSES) {if (!ClassUtils.isPresent(className, null)) {return WebApplicationType.NONE;}}return WebApplicationType.SERVLET; }private static final String REACTIVE_WEB_ENVIRONMENT_CLASS = "org.springframework."+ "web.reactive.DispatcherHandler";private static final String MVC_WEB_ENVIRONMENT_CLASS = "org.springframework."+ "web.servlet.DispatcherServlet";private static final String[] WEB_ENVIRONMENT_CLASSES = { "javax.servlet.Servlet","org.springframework.web.context.ConfigurableWebApplicationContext"}; public enum WebApplicationType {/*** 非 WEB 項目*/NONE,/*** SERVLET WEB 項目*/SERVLET,/*** 響應式 WEB 項目*/REACTIVE}這個就是根據類路徑下是否有對應項目類型的類推斷出不同的應用類型。
5. 設置應用上線文初始化器
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));ApplicationContextInitializer?的作用是什么?源碼如下。
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {/*** Initialize the given application context.* @param applicationContext the application to configure*/void initialize(C applicationContext);} }用來初始化指定的 Spring 應用上下文,如注冊屬性資源、激活 Profiles 等。
來看下 setInitializers 方法源碼,其實就是初始化一個 ApplicationContextInitializer 應用上下文初始化器實例的集合。
?
再來看下這個初始化 getSpringFactoriesInstances 方法和相關的源碼:
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {return getSpringFactoriesInstances(type, new Class<?>[] {}); }private <T> Collection<T> getSpringFactoriesInstances(Class<T> type,Class<?>[] parameterTypes, Object... args) {ClassLoader classLoader = Thread.currentThread().getContextClassLoader();// Use names and ensure unique to protect against duplicatesSet<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));List<T> instances = createSpringFactoriesInstances(type, parameterTypes,classLoader, args, names);AnnotationAwareOrderComparator.sort(instances);return instances; }設置應用上下文初始化器可分為以下 5 個步驟。
- 5.1 獲取當前線程上下文類加載器
5.2 獲取 `ApplicationContextInitializer 的實例名稱集合并去重
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));loadFactoryNames?方法相關的源碼如下:
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {String factoryClassName = factoryClass.getName();return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList()); }public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {MultiValueMap<String, String> result = cache.get(classLoader);if (result != null) {return result;}try {Enumeration<URL> urls = (classLoader != null ?classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));result = new LinkedMultiValueMap<>();while (urls.hasMoreElements()) {URL url = urls.nextElement();UrlResource resource = new UrlResource(url);Properties properties = PropertiesLoaderUtils.loadProperties(resource);for (Map.Entry<?, ?> entry : properties.entrySet()) {List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));result.addAll((String) entry.getKey(), factoryClassNames);}}cache.put(classLoader, result);return result;}catch (IOException ex) {throw new IllegalArgumentException("Unable to load factories from location [" +FACTORIES_RESOURCE_LOCATION + "]", ex);} }根據類路徑下的 META-INF/spring.factories 文件解析并獲取 ApplicationContextInitializer 接口的所有配置的類路徑名稱。
spring-boot-autoconfigure-2.0.3.RELEASE.jar!/META-INF/spring.factories 的初始化器相關配置內容如下:
# Initializers org.springframework.context.ApplicationContextInitializer=\ org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\ org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener5.3 根據以上類路徑創建初始化器實例列表
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,classLoader, args, names);private <T> List<T> createSpringFactoriesInstances(Class<T> type,Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args,Set<String> names) {List<T> instances = new ArrayList<>(names.size());for (String name : names) {try {Class<?> instanceClass = ClassUtils.forName(name, classLoader);Assert.isAssignable(type, instanceClass);Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);T instance = (T) BeanUtils.instantiateClass(constructor, args);instances.add(instance);}catch (Throwable ex) {throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);}}return instances; }5.4 初始化器實例列表排序
AnnotationAwareOrderComparator.sort(instances);5.5 返回初始化器實例列表
return instances;6. 設置監聽器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));ApplicationListener?的作用是什么?源碼如下。
@FunctionalInterface public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {/*** Handle an application event.* @param event the event to respond to*/void onApplicationEvent(E event);}看源碼,這個接口繼承了 JDK 的 java.util.EventListener 接口,實現了觀察者模式,它一般用來定義感興趣的事件類型,事件類型限定于 ApplicationEvent的子類,這同樣繼承了 JDK 的 java.util.EventObject 接口。
設置監聽器和設置初始化器調用的方法是一樣的,只是傳入的類型不一樣,設置監聽器的接口類型為: getSpringFactoriesInstances,對應的 spring-boot-autoconfigure-2.0.3.RELEASE.jar!/META-INF/spring.factories 文件配置內容請見下方。
# Application Listeners org.springframework.context.ApplicationListener=\ org.springframework.boot.autoconfigure.BackgroundPreinitializer可以看出目前只有一個?BackgroundPreinitializer?監聽器。
7.推斷主入口應用類
這個推斷入口應用類的方式有點特別,通過構造一個運行時異常,再遍歷異常棧中的方法名,獲取方法名為 main 的棧幀,從來得到入口類的名字再返回該類。
總結
源碼分析內容有點多,也很麻煩,本章暫時分析到 SpringApplication 構造方法的初始化流程,下章再繼續分析其 run 方法
第二篇
SpringApplication 實例 run 方法運行過程
上面分析了?SpringApplication?實例對象構造方法初始化過程,下面繼續來看下這個?SpringApplication?對象的?run?方法的源碼和運行流程。
public ConfigurableApplicationContext run(String... args) {// 1、創建并啟動計時監控類StopWatch stopWatch = new StopWatch();stopWatch.start();// 2、初始化應用上下文和異常報告集合ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();// 3、設置系統屬性 `java.awt.headless` 的值,默認值為:trueconfigureHeadlessProperty();// 4、創建所有 Spring 運行監聽器并發布應用啟動事件SpringApplicationRunListeners listeners = getRunListeners(args);listeners.starting();try {// 5、初始化默認應用參數類ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);// 6、根據運行監聽器和應用參數來準備 Spring 環境ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments);configureIgnoreBeanInfo(environment);// 7、創建 Banner 打印類Banner printedBanner = printBanner(environment);// 8、創建應用上下文context = createApplicationContext();// 9、準備異常報告器exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class }, context);// 10、準備應用上下文prepareContext(context, environment, listeners, applicationArguments,printedBanner);// 11、刷新應用上下文refreshContext(context);// 12、應用上下文刷新后置處理afterRefresh(context, applicationArguments);// 13、停止計時監控類stopWatch.stop();// 14、輸出日志記錄執行主類名、時間信息if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);}// 15、發布應用上下文啟動完成事件listeners.started(context);// 16、執行所有 Runner 運行器callRunners(context, applicationArguments);}catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, listeners);throw new IllegalStateException(ex);}try {// 17、發布應用上下文就緒事件listeners.running(context);}catch (Throwable ex) {handleRunFailure(context, ex, exceptionReporters, null);throw new IllegalStateException(ex);}// 18、返回應用上下文return context; }所以,我們可以按以下幾步來分解?run方法的啟動過程。
1、創建并啟動計時監控類
StopWatch stopWatch = new StopWatch(); stopWatch.start();來看下這個計時監控類 StopWatch 的相關源碼:
public void start() throws IllegalStateException {start(""); }public void start(String taskName) throws IllegalStateException {if (this.currentTaskName != null) {throw new IllegalStateException("Can't start StopWatch: it's already running");}this.currentTaskName = taskName;this.startTimeMillis = System.currentTimeMillis(); }首先記錄了當前任務的名稱,默認為空字符串,然后記錄當前 Spring Boot 應用啟動的開始時間。
2、初始化應用上下文和異常報告集合
3、設置系統屬性?java.awt.headless?的值
configureHeadlessProperty();設置該默認值為:true,Java.awt.headless = true 有什么作用?
對于一個 Java 服務器來說經常要處理一些圖形元素,例如地圖的創建或者圖形和圖表等。這些API基本上總是需要運行一個X-server以便能使用AWT(Abstract Window Toolkit,抽象窗口工具集)。然而運行一個不必要的 X-server 并不是一種好的管理方式。有時你甚至不能運行 X-server,因此最好的方案是運行 headless 服務器,來進行簡單的圖像處理。
參考:www.cnblogs.com/princessd8251/p/4000016.html
4、創建所有 Spring 運行監聽器并發布應用啟動事件
?
來看下創建 Spring 運行監聽器相關的源碼:
private SpringApplicationRunListeners getRunListeners(String[] args) {Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args)); }SpringApplicationRunListeners(Log log,Collection<? extends SpringApplicationRunListener> listeners) {this.log = log;this.listeners = new ArrayList<>(listeners); }創建邏輯和之前實例化初始化器和監聽器的一樣,一樣調用的是 getSpringFactoriesInstances 方法來獲取配置的監聽器名稱并實例化所有的類。
SpringApplicationRunListener 所有監聽器配置在 spring-boot-2.0.3.RELEASE.jar!/META-INF/spring.factories 這個配置文件里面。
# Run Listeners org.springframework.boot.SpringApplicationRunListener=\ org.springframework.boot.context.event.EventPublishingRunListener5、初始化默認應用參數類
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);6、根據運行監聽器和應用參數來準備 Spring 環境
ConfigurableEnvironment environment = prepareEnvironment(listeners,applicationArguments); configureIgnoreBeanInfo(environment);下面我們主要來看下準備環境的 prepareEnvironment 源碼:
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,ApplicationArguments applicationArguments) {// 6.1) 獲取(或者創建)應用環境ConfigurableEnvironment environment = getOrCreateEnvironment();// 6.2) 配置應用環境configureEnvironment(environment, applicationArguments.getSourceArgs());listeners.environmentPrepared(environment);bindToSpringApplication(environment);if (this.webApplicationType == WebApplicationType.NONE) {environment = new EnvironmentConverter(getClassLoader()).convertToStandardEnvironmentIfNecessary(environment);}ConfigurationPropertySources.attach(environment);return environment; }6.1 獲取(或者創建)應用環境
private ConfigurableEnvironment getOrCreateEnvironment() {if (this.environment != null) {return this.environment;}if (this.webApplicationType == WebApplicationType.SERVLET) {return new StandardServletEnvironment();}return new StandardEnvironment(); }這里分為標準?Servlet?環境和標準環境。
- 6.2 配置應用環境
這里分為以下兩步來配置應用環境。
- 配置 property sources
- 配置 Profiles
這里主要處理所有 property sources 配置和 profiles 配置。
7、創建 Banner 打印類
Banner printedBanner = printBanner(environment);這是用來打印 Banner 的處理類,這個沒什么好說的。
8、創建應用上下文
context = createApplicationContext();來看下?createApplicationContext()?方法的源碼:
protected ConfigurableApplicationContext createApplicationContext() {Class<?> contextClass = this.applicationContextClass;if (contextClass == null) {try {switch (this.webApplicationType) {case SERVLET:contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);break;case REACTIVE:contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);break;default:contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);}}catch (ClassNotFoundException ex) {throw new IllegalStateException("Unable create a default ApplicationContext, "+ "please specify an ApplicationContextClass",ex);}}return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass); }其實就是根據不同的應用類型初始化不同的上下文應用類。
9、準備異常報告器
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,new Class[] { ConfigurableApplicationContext.class }, context);邏輯和之前實例化初始化器和監聽器的一樣,一樣調用的是 getSpringFactoriesInstances 方法來獲取配置的異常類名稱并實例化所有的異常處理類。
該異常報告處理類配置在 spring-boot-2.0.3.RELEASE.jar!/META-INF/spring.factories 這個配置文件里面。
?
10、準備應用上下文
prepareContext(context, environment, listeners, applicationArguments,printedBanner);來看下?prepareContext()?方法的源碼:
private void prepareContext(ConfigurableApplicationContext context,ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,ApplicationArguments applicationArguments, Banner printedBanner) {// 10.1)綁定環境到上下文context.setEnvironment(environment);// 10.2)配置上下文的 bean 生成器及資源加載器postProcessApplicationContext(context);// 10.3)為上下文應用所有初始化器applyInitializers(context);// 10.4)觸發所有 SpringApplicationRunListener 監聽器的 contextPrepared 事件方法listeners.contextPrepared(context);// 10.5)記錄啟動日志if (this.logStartupInfo) {logStartupInfo(context.getParent() == null);logStartupProfileInfo(context);}// 10.6)注冊兩個特殊的單例beancontext.getBeanFactory().registerSingleton("springApplicationArguments",applicationArguments);if (printedBanner != null) {context.getBeanFactory().registerSingleton("springBootBanner", printedBanner);}// 10.7)加載所有資源Set<Object> sources = getAllSources();Assert.notEmpty(sources, "Sources must not be empty");load(context, sources.toArray(new Object[0]));// 10.8)觸發所有 SpringApplicationRunListener 監聽器的 contextLoaded 事件方法listeners.contextLoaded(context); }11、刷新應用上下文
refreshContext(context);這個主要是刷新 Spring 的應用上下文,源碼如下,不詳細說明。
private void refreshContext(ConfigurableApplicationContext context) {refresh(context);if (this.registerShutdownHook) {try {context.registerShutdownHook();}catch (AccessControlException ex) {// Not allowed in some environments.}} }這個主要是刷新 Spring 的應用上下文,源碼如下,不詳細說明。
private void refreshContext(ConfigurableApplicationContext context) {refresh(context);if (this.registerShutdownHook) {try {context.registerShutdownHook();}catch (AccessControlException ex) {// Not allowed in some environments.}} }12、應用上下文刷新后置處理
afterRefresh(context, applicationArguments);看了下這個方法的源碼是空的,目前可以做一些自定義的后置處理操作。
/*** Called after the context has been refreshed.* @param context the application context* @param args the application arguments*/ protected void afterRefresh(ConfigurableApplicationContext context,ApplicationArguments args) { }13、停止計時監控類
stopWatch.stop(); public void stop() throws IllegalStateException {if (this.currentTaskName == null) {throw new IllegalStateException("Can't stop StopWatch: it's not running");}long lastTime = System.currentTimeMillis() - this.startTimeMillis;this.totalTimeMillis += lastTime;this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);if (this.keepTaskList) {this.taskList.add(this.lastTaskInfo);}++this.taskCount;this.currentTaskName = null; } ```java 計時監聽器停止,并統計一些任務執行信息。**14、輸出日志記錄執行主類名、時間信息** ```java if (this.logStartupInfo) {new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); }15、發布應用上下文啟動完成事件
listeners.started(context);觸發所有?SpringApplicationRunListener?監聽器的?started?事件方法。
16、執行所有 Runner 運行器
callRunners(context, applicationArguments); private void callRunners(ApplicationContext context, ApplicationArguments args) {List<Object> runners = new ArrayList<>();runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());AnnotationAwareOrderComparator.sort(runners);for (Object runner : new LinkedHashSet<>(runners)) {if (runner instanceof ApplicationRunner) {callRunner((ApplicationRunner) runner, args);}if (runner instanceof CommandLineRunner) {callRunner((CommandLineRunner) runner, args);}} }執行所有 ApplicationRunner 和 CommandLineRunner 這兩種運行器,不詳細展開了。
17、發布應用上下文就緒事件
listeners.running(context);
觸發所有 SpringApplicationRunListener 監聽器的 running 事件方法。
18、返回應用上下文
?
?
總結
Spring Boot 的啟動全過程源碼分析至此,分析 Spring 源碼真是一個痛苦的過程,希望能給大家提供一點參考和思路,也希望能給正在 Spring Boot 學習路上的朋友一點收獲。
?
總結
以上是生活随笔為你收集整理的SpringBoot2.x启动原理概述的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常用json框架介绍和Jackson返回
- 下一篇: 茅塞顿开:Spring Aware原理解