springboot源碼解析(轉)
一.Spring Boot 的入口類
@SpringBootApplication
public class StartupApplication {
public static void main(String[] args) {
SpringApplication.run(StartupApplication.class, args);
}
}
第一個參數 resourceLoader:資源加載器
第二個參數 primarySources:加載的主要資源類
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
// 1、資源初始化資源加載器爲 null,默認爲空
this.resourceLoader = resourceLoader;
// 2、斷言主要加載資源類不能爲 null,否則報錯
Assert.notNull(primarySources, "PrimarySources must not be null");
// 3、初始化主要加載資源類集合並去重
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// 4、推斷當前 WEB 應用類型,一共有三種:
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//5、設置應用上線文初始化器,從"META-INF/spring.factories"讀取ApplicationContextInitializer類的實例名稱集合並去重,並進行set去重。(一共4個)
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
// 6、設置監聽器,從"META-INF/spring.factories"讀取ApplicationListener類的實例名稱集合並去重,並進行set去重。(一共10個)
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 7、推斷主入口應用類,通過當前調用棧,獲取Main方法所在類,並賦值給mainApplicationClass。
this.mainApplicationClass = deduceMainApplicationClass();
}
1.詳細看看deduceFromClasspath方法的實現:
static WebApplicationType deduceFromClasspath() {
if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
return WebApplicationType.REACTIVE;
}
for (String className : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(className, null)) {
return WebApplicationType.NONE;
}
}
return WebApplicationType.SERVLET;
}
public enum WebApplicationType {
//非 WEB 項目
NONE,
//SERVLET WEB 項目
SERVLET,
//響應式 WEB 項目
REACTIVE;
}
二.springboot啓動類
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` 的值,默認值爲:true,用於運行headless服務器,進行簡單的圖像處理
configureHeadlessProperty();
// 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;
}
三.啓動詳解
1、創建並啓動計時監控類
StopWatch stopWatch = new StopWatch();
stopWatch.start();
來看下這個計時監控類 StopWatch 的相關源碼:
作用:
- 首先記錄了當前任務的名稱,默認爲空字符串,然後記錄當前 Spring Boot 應用啓動的開始時間
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();
}
2、初始化應用上下文和異常報告集合
ConfigurableApplicationContext context = null;
Collection exceptionReporters = new
ArrayList<>();
3、設置系統屬性 java.awt.headless
的值
configureHeadlessProperty();
4、創建所有 Spring 運行監聽器併發布應用啓動事件
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
來看下創建 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);
}
5、初始化默認應用參數類
ApplicationArguments applicationArguments = newDefaultApplicationArguments(String[] args);
6.下面我們主要來看下準備環境的 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) 配置應用環境
protected void configureEnvironment(ConfigurableEnvironment environment,
String[] args) {
configurePropertySources(environment, args);
configureProfiles(environment, args);
}
6.2)這裏分爲以下兩步來配置應用環境。
配置 property sources
配置 Profiles
這裏主要處理所有 property sources 配置和 profiles配置。
7、創建 Banner 打印類
Banner printedBanner = printBanner(environment);
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);
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)註冊兩個特殊的單例bean
context.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.
}
}
}
12、應用上下文刷新後置處理
afterRefresh(context, applicationArguments);
看了下這個方法的源碼是空的,目前可以做一些自定義的後置處理操作。
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;
}
計時監聽器停止,並統計一些任務執行信息。
14、輸出日誌記錄執行主類名、時間信息
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、返回應用上下文
return context;