Springboot啟動原理
Springboot啟動原理
public static void main(String[] args) {
//xxx.class:主配置類,(可以傳多個)
SpringApplication.run(xxx.class, args);
}
1. 從run方法開始,建立SpringApplication,然後再呼叫run方法
/** * ConfigurableApplicationContext(可配置的應用程式上下文) */ public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { //呼叫下面的run方法 return run(new Class[]{primarySource}, args); } public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { //primarySources:主配置類 return (new SpringApplication(primarySources)).run(args); }
2. 建立SpringApplication
public SpringApplication(Class<?>... primarySources) {
//呼叫下面構造方法
this((ResourceLoader) null, primarySources);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { //獲取類載入器 this.resourceLoader = resourceLoader; //檢視類載入器是否為空 Assert.notNull(primarySources, "PrimarySources must not be null"); // 儲存主配置類的資訊到一個雜湊連結串列集合中,方便查詢呼叫增刪 this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); //獲取當前應用的型別,是不是web應用,見2.1 this.webApplicationType = WebApplicationType.deduceFromClasspath(); //從類路徑下找到META‐INF/spring.factories配置的所有ApplicationContextInitializer;然後儲存起來,見2.2 setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); //從類路徑下找到META‐INF/spring.factories配置的所有spring.ApplicationListener;然後儲存起來,原理同上 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); //從多個SpringApplication中找到有main方法的主SpringApplication(在調run方法的時候是可以傳遞多個配置類的) //只記錄有main方法的類名,以便下一步的run this.mainApplicationClass = deduceMainApplicationClass(); }
2.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; }
2.2 getSpringFactoriesInstances
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
// Use names and ensure unique to protect against duplicates
// 配置的所有ApplicationContextInitializer等分別到一個集合中以便查詢使用,其中loadFactoryNames方法從類路徑下找到META‐INF/spring.factories中傳入的parameterTypes
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
// 例項化傳入的類
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
// 排序以便提高針對他執行操作的效率
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
2.3 deduceMainApplicationClass
private Class<?> deduceMainApplicationClass() {
try {
// 查詢當前的虛擬機器的當前執行緒的StackTrace資訊
StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
// 檢視當前執行緒中已載入的類中有沒有main方法
if ("main".equals(stackTraceElement.getMethodName())) {
//有則返回該類的類名
return Class.forName(stackTraceElement.getClassName());
}
}
}
catch (ClassNotFoundException ex) {
// Swallow and continue
}
return null;
}
StackTrace簡述
1 StackTrace用棧的形式儲存了方法的呼叫資訊.
2 怎麼獲取這些呼叫資訊呢?
可用Thread.currentThread().getStackTrace()方法得到當前執行緒的StackTrace資訊.該方法返回的是一個StackTraceElement陣列.
3 該StackTraceElement陣列就是StackTrace中的內容.
4 遍歷該StackTraceElement陣列.就可以看到方法間的呼叫流程.
比如執行緒中methodA呼叫了methodB那麼methodA先入棧methodB再入棧.
5 在StackTraceElement陣列下標為2的元素中儲存了當前方法的所屬檔名,當前方法所屬的類名,以及該方法的名字
除此以外還可以獲取方法呼叫的行數.
6 在StackTraceElement陣列下標為3的元素中儲存了當前方法的呼叫者的資訊和它呼叫時的程式碼行數.
3. 呼叫SpringApplication物件的run方法
public ConfigurableApplicationContext run(String... args) {
//Simple stop watch, allowing for timing of a number of tasks, exposing totalrunning time and running time for each named task.簡單來說是建立ioc容器的計時器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
//宣告IOC容器
ConfigurableApplicationContext context = null;
//異常報告儲存列表
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
//載入圖形化配置
this.configureHeadlessProperty();
//從類路徑下META‐INF/spring.factories獲取SpringApplicationRunListeners,原理同2中獲取ApplicationContextInitializer和ApplicationListener
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//遍歷上一步獲取的所有SpringApplicationRunListener,呼叫其starting方法
listeners.starting();
Collection exceptionReporters;
try {
//封裝命令列
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//準備環境,把上面獲取到的SpringApplicationRunListeners傳過去,見3.1
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
//列印Banner,就是控制檯那個Spring字元畫
Banner printedBanner = this.printBanner(environment);
//根據當前環境利用反射建立IOC容器,見3.2
context = this.createApplicationContext();
//從類路徑下META‐INF/spring.factories獲取SpringBootExceptionReporter,原理同2中獲取ApplicationContextInitializer和ApplicationListener
exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//準備IOC容器,見3.3
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
//重新整理IOC容器,可檢視配置嵌入式Servlet容器原理,所有的@Configuration和@AutoConfigutation等Bean物件全在此時加入容器中,並依據不同的選項建立了不同功能如伺服器/資料庫等元件。見3.4
//可以說@SpringbootApplication中自動掃描包和Autoconfiguration也是在此時進行的
this.refreshContext(context);
//這是一個空方法
this.afterRefresh(context, applicationArguments);
//停止計時,列印時間
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
//呼叫所有SpringApplicationRunListener的started方法
listeners.started(context);
//見3.5 ,從ioc容器中獲取所有的ApplicationRunner和CommandLineRunner進行回撥ApplicationRunner先回調,CommandLineRunner再回調。
this.callRunners(context, applicationArguments);
} catch (Throwable var10) {
this.handleRunFailure(context, var10, exceptionReporters, listeners);
throw new IllegalStateException(var10);
}
try {
//呼叫所有SpringApplicationRunListener的running方法
listeners.running(context);
//返回建立好的ioc容器,啟動完成
return context;
} catch (Throwable var9) {
this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
throw new IllegalStateException(var9);
}
}
3.1 prepareEnvironment
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
//獲取或者建立環境,有則獲取,無則建立
ConfigurableEnvironment environment = this.getOrCreateEnvironment();
//配置環境
this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach((Environment)environment);
//建立環境完成後,ApplicationContext建立前,呼叫前面獲取的所有SpringApplicationRunListener的environmentPrepared方法,讀取配置檔案使之生效
listeners.environmentPrepared((ConfigurableEnvironment)environment);
// 環境搭建好後,需依據他改變Apllication的引數,將enviroment的資訊放置到Binder中,再由Binder依據不同的條件將“spring.main”SpringApplication更改為不同的環境,為後面context的建立搭建環境
//為什麼boot要這樣做,其實咱們啟動一個boot的時候並不是一定只有一個Application且用main方式啟動。這樣子我們可以讀取souces配置多的Application
this.bindToSpringApplication((ConfigurableEnvironment)environment);
if (!this.isCustomEnvironment) {
environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
}
ConfigurationPropertySources.attach((Environment)environment);
//回到3,將建立好的environment返回
return (ConfigurableEnvironment)environment;
}
3.2 createApplicationContext
protected ConfigurableApplicationContext createApplicationContext() {
//獲取當前Application中ioc容器類
Class<?> contextClass = this.applicationContextClass;
//若沒有則依據該應用是否為web應用而建立相應的ioc容器
//除非為其傳入applicationContext,不然Application的預設構造方法並不會建立ioc容器
if (contextClass == null) {
try {
switch(this.webApplicationType) {
case SERVLET:
contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
break;
case REACTIVE:
contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
break;
default:
contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
}
} catch (ClassNotFoundException var3) {
throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
}
}
//用bean工具類例項化ioc容器物件並返回。回到3
return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}
3.3 prepareContext
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
//將建立好的環境放到IOC容器中
context.setEnvironment(environment);
//處理一些元件,沒有實現postProcessA介面
this.postProcessApplicationContext(context);
//獲取所有的ApplicationContextInitializer呼叫其initialize方法,這些ApplicationContextInitializer就是在2步驟中獲取的,見3.3.1
this.applyInitializers(context);
//回撥所有的SpringApplicationRunListener的contextPrepared方法,這些SpringApplicationRunListeners是在步驟3中獲取的
listeners.contextPrepared(context);
//列印日誌
if (this.logStartupInfo) {
this.logStartupInfo(context.getParent() == null);
this.logStartupProfileInfo(context);
}
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//將一些applicationArguments註冊成容器工廠中的單例物件
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory)beanFactory).setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
//若是延遲載入,則在ioc容器中加入LazyInitializationBeanFactoryPostProcessor,
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
//獲取所有報告primarySources在內的所有source
Set<Object> sources = this.getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
//載入容器
this.load(context, sources.toArray(new Object[0]));
//回撥所有的SpringApplicationRunListener的contextLoaded方法
listeners.contextLoaded(context);
}
3.3.1 applyInitializers
protected void applyInitializers(ConfigurableApplicationContext context) {
Iterator var2 = this.getInitializers().iterator();
while(var2.hasNext()) {
//將之前的所有的ApplicationContextInitializer遍歷
ApplicationContextInitializer initializer = (ApplicationContextInitializer)var2.next();
//解析檢視之前從spring.factories呼叫的ApplicationContextInitializer是否能被ioc容器呼叫
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(), ApplicationContextInitializer.class);
Assert.isInstanceOf(requiredType, context, "Unable to call initializer.");
//可以呼叫則對ioc容器進行初始化(還沒載入我們自己配置的bean和AutoConfiguration那些)
initializer.initialize(context);
}
}//返回3.3
3.4 refreshment(context)
@Override
//詳情見內建Servlet的啟動原理,最後是用ApplicationContext的實現類的refresh()方法,若是web Application則為ServletWebServerApplicationContext
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
3.5 callRunners
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList();
//將ioc容器中的的ApplicationRunner和CommandLineRunner(),在建立ioc容器時建立的
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
Iterator var4 = (new LinkedHashSet(runners)).iterator();
//呼叫ApplicationRunner和CommandLineRunner的run方法
while(var4.hasNext()) {
Object runner = var4.next();
if (runner instanceof ApplicationRunner) {
this.callRunner((ApplicationRunner)runner, args);
}
if (runner instanceof CommandLineRunner) {
this.callRunner((CommandLineRunner)runner, args);
}
}
}
配置在META-INF/spring.factories
- ApplicationContextInitializer(在我們將enviroment繫結到application後可以用來建立不同型別的context)
- SpringApplicationRunListener(在Application 建立/執行/銷燬等進行一些我們想要的特殊配置)
只需要放在ioc容器中
- ApplicationRunner(載入沒有在ApplicationContext中的bean時讓bean能載入)
- CommandLineRunner(命令列執行器)
Application初始化元件測試
-
建立
ApplicationContextInitializer
和SpringApplicationRunListener
的實現類,並在META-INF/spring.factories檔案中配置public class TestApplicationContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext configurableApplicationContext) { System.out.println("TestApplicationContextInitializer.initialize"); } }
public class TestSpringApplicationRunListener implements SpringApplicationRunListener { @Override public void starting() { System.out.println("TestSpringApplicationRunListener.starting"); } @Override public void environmentPrepared(ConfigurableEnvironment environment) { System.out.println("TestSpringApplicationRunListener.environmentPrepared"); } @Override public void contextPrepared(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.contextPrepared"); } @Override public void contextLoaded(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.contextLoaded"); } @Override public void started(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.started"); } @Override public void running(ConfigurableApplicationContext context) { System.out.println("TestSpringApplicationRunListener.running"); } @Override public void failed(ConfigurableApplicationContext context, Throwable exception) { System.out.println("TestSpringApplicationRunListener.failed"); } }
org.springframework.context.ApplicationContextInitializer=\ cn.clboy.springbootprocess.init.TestApplicationContextInitializer org.springframework.boot.SpringApplicationRunListener=\ cn.clboy.springbootprocess.init.TestSpringApplicationRunListener
啟動報錯:說是沒有找到帶org.springframework.boot.SpringApplication和String陣列型別引數的構造器,給TestSpringApplicationRunListener新增這樣的構造器
public TestSpringApplicationRunListener(SpringApplication application,String[] args) { }
-
建立
ApplicationRunner
實現類和CommandLineRunner
實現類,因為是從ioc容器完成建立後中提取存放在裡面的這兩個Runner,因此可以直接新增到容器中,最後callRunner使用@Component public class TestApplicationRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("TestApplicationRunner.run\t--->"+args); } }
@Component public class TestCommandLineRunn implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("TestCommandLineRunn.runt\t--->"+ Arrays.toString(args)); } }