SpringBoot應用啟動過程分析
真的好奇害死貓!之前寫過幾個SpringBoot應用,但是一直沒搞明白應用到底是怎麽啟動的,心裏一直有點膈應。好吧,趁有空去看了下源碼,寫下這篇博客作為學習記錄吧!
個人拙見,若哪裏有理解不對的地方,請各路大神指正,小弟不勝感激!
一.應用啟動類
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
開發SpirngBoot應用時,入口類就這簡單的幾行。但是卻完成了N多服務的初始化、加載和發布。那麽這幾行代碼究竟幹了什麽呢,SpringBoot應用到底是怎麽啟動的。
二.@SpringBootApplication註解
2.1.SpringBootApplication註解
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication {
@SpringBootApplication=@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan
2.2.@SpringBootConfiguration
/** * Indicates that a class Spring Boot application * {@link Configuration @Configuration}. Can be used as an alternative to the Spring‘s * standard {@code @Configuration} annotation so that configuration can be found * automatically (for example in tests). */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration public @interface SpringBootConfiguration { }
SpringBootConfiguration註解和Spring的@Configuration註解作用一樣。標註當前類是配置類,並會將當前類內聲明的一個或多個以@Bean註解標記的方法的實例納入到spring容器中。比如容器加載時,會生成Hello的Bean加載到IOC容器中。
@SpringBootConfiguration
public class ExampleConfig {
@Bean
public void Hello(){
System.out.println("hello");
}
}
2.3.@EnableAutoConfiguration
@SuppressWarnings("deprecation")
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
}
這個註解是SpringBoot能進行自動配置的關鍵。@Import註解用於導入配置類,我們看下導入類EnableAutoConfigurationImportSelector。容器刷新時,會調用AutoConfigurationImportSelector類的selectImports方法,掃描META-INF/spring.factories文件自動配置類(key為EnableAutoConfiguration),然後Spring容器處理配置類。(對Spring的一些加載過程不清晰,我是相當的迷啊)
2.4.@ComponentScan
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
/**
* Configures component scanning directives for use with @{@link Configuration} classes.
* Provides support parallel with Spring XML‘s {@code <context:component-scan>} element.
*
* <p>Either {@link #basePackageClasses} or {@link #basePackages} (or its alias
* {@link #value}) may be specified to define specific packages to scan. If specific
* packages are not defined, scanning will occur from the package of the
* class that declares this annotation.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan
@ComponentScan掃描指定的包路徑,若未指定包路徑,則以聲明這個註解的類作為基本包路徑。比如@SpringBootApplication就沒有指定包路徑,則DemoApplication的包路徑將作為掃描的基本包路徑,因此強烈建議將主類放在頂層目錄下。
excludeFilters屬性指定哪些類型不符合組件掃描的條件,會在掃描的時候過濾掉。
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)
比如上面這段代碼。@Filter聲明了過濾器類型類為自定義類型(需要實現TypeFilter接口),過濾器為AutoConfigurationExcludeFilter。當match方法為true,返回掃描類對象,否則過濾掉。但是要註意@ComponentScan的key為excludeFilters,因此這些類型將在包掃描的時候過濾掉,也就是說,ComponentScan在掃描時,發現當前掃描類滿足macth的條件(match返回true),是不會將該類加載到容器的。
//metadataReader 表示讀取到的當前正在掃描的類的信息
//metadataReaderFactory 表示可以獲得到其他任何類的信息
@Override
public boolean match(MetadataReader metadataReader,
MetadataReaderFactory metadataReaderFactory) throws IOException {
return isConfiguration(metadataReader) && isAutoConfiguration(metadataReader);
}
//該類是帶有Configuration註解的配置類
private boolean isConfiguration(MetadataReader metadataReader) {
return metadataReader.getAnnotationMetadata()
.isAnnotated(Configuration.class.getName());
}
//該類是否為spring.factory配置的自動配置類
private boolean isAutoConfiguration(MetadataReader metadataReader) {
return getAutoConfigurations()
.contains(metadataReader.getClassMetadata().getClassName());
}
三.run(DemoApplication.class, args)解析
3.1.進入SpringApplication
public static ConfigurableApplicationContext run(Class<?>[] primarySources,
String[] args) {
return new SpringApplication(primarySources).run(args);
}
我們根據DemoApplication跟進代碼,發現其調用的SpringApplication類的run方法。這個方法就幹了2件事:一是創建SpringApplication對象,二是啟動SpringApplication。
3.2.SpringApplication構造器分析
1.構造器
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
/**
* Create a new {@link SpringApplication} instance. The application context will load
* beans from the specified primary sources
*/
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應用,servlet類型web應用和非web應用,在後面用於確定實例化applicationContext的類型
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//設置初始化器,讀取spring.factories文件key ApplicationContextInitializer對應的value並實例化
//ApplicationContextInitializer接口用於在Spring上下文被刷新之前進行初始化的操作
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
//設置監聽器,讀取spring.factories文件key ApplicationListener對應的value並實例化
// interface ApplicationListener<E extends ApplicationEvent> extends EventListener
//ApplicationListener繼承EventListener,實現了觀察者模式。對於Spring框架的觀察者模式實現,它限定感興趣的事件類型需要是ApplicationEvent類型事件
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
//沒啥特別作用,僅用於獲取入口類class對象
this.mainApplicationClass = deduceMainApplicationClass();
}
在構造器裏主要幹了2件事,一個設置初始化器,二是設置監聽器。
2.設置初始化器
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
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 = getClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<>(
//從類路徑的META-INF處讀取相應配置文件spring.factories,然後進行遍歷,讀取配置文件中Key(type)對應的value
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
//將names的對象實例化
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
根據入參type類型ApplicationContextInitializer.class從類路徑的META-INF處讀取相應配置文件spring.factories並實例化對應Initializer。上面這2個函數後面會反復用到。
org.springframework.context.ApplicationContextInitializer=org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,org.springframework.boot.context.ContextIdApplicationContextInitializer,org.springframework.boot.context.config.DelegatingApplicationContextInitializer,org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
3.設置監聽器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
和設置初始化器一個套路,通過getSpringFactoriesInstances函數實例化監聽器。
org.springframework.context.ApplicationListener=org.springframework.boot.ClearCachesApplicationListener,org.springframework.boot.builder.ParentContextCloserApplicationListener,org.springframework.boot.context.FileEncodingApplicationListener,org.springframework.boot.context.config.AnsiOutputApplicationListener,org.springframework.boot.context.config.ConfigFileApplicationListener,org.springframework.boot.context.config.DelegatingApplicationListener,org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,org.springframework.boot.context.logging.LoggingApplicationListener,org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener
3.3.run(String... args)解析
1.run函數
/**
* Run the Spring application, creating and refreshing a new ApplicationContext
*/
public ConfigurableApplicationContext run(String... args) {
//計時器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//設置java.awt.headless系統屬性為true,Headless模式是系統的一種配置模式。
// 在該模式下,系統缺少了顯示設備、鍵盤或鼠標。但是服務器生成的數據需要提供給顯示設備等使用。
// 因此使用headless模式,一般是在程序開始激活headless模式,告訴程序,現在你要工作在Headless mode下,依靠系統的計算能力模擬出這些特性來
configureHeadlessProperty();
//獲取監聽器集合對象
SpringApplicationRunListeners listeners = getRunListeners(args);
//發出開始執行的事件。
listeners.starting();
try {
//根據main函數傳入的參數,創建DefaultApplicationArguments對象
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//根據掃描到的監聽器對象和函數傳入參數,進行環境準備。
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
//和上面套路一樣,讀取spring.factories文件key SpringBootExceptionReporter對應的value
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//和上面的一樣,context準備完成之後,將觸發SpringApplicationRunListener的contextPrepared執行
refreshContext(context);
//其實啥也沒幹。但是老版本的callRunners好像是在這裏執行的。
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
//發布ApplicationStartedEvent事件,發出結束執行的事件
listeners.started(context);
//在某些情況下,我們希望在容器bean加載完成後執行一些操作,會實現ApplicationRunner或者CommandLineRunner接口
//後置操作,就是在容器完成刷新後,依次調用註冊的Runners,還可以通過@Order註解設置各runner的執行順序。
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
2.獲取run listeners
SpringApplicationRunListeners listeners = getRunListeners(args);
和構造器設置初始化器一個套路,根據傳入type SpringApplicationRunListener去掃描spring.factories文件,讀取type對應的value並實例化。然後利用實例化對象創建SpringApplicationRunListeners對象。
org.springframework.boot.SpringApplicationRunListener=org.springframework.boot.context.event.EventPublishingRunListener
EventPublishingRunListener的作用是發布SpringApplicationEvent事件。
EventPublishingRunListener更像是被監聽對象,這個命名讓我有點迷。
public class EventPublishingRunListener implements SpringApplicationRunListener, Ordered {
......
@Override
public void starting() {
this.initialMulticaster.multicastEvent(
new ApplicationStartingEvent(this.application, this.args));
}
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(
this.application, this.args, environment));
}
........
}
3.發出開始執行的事件
listeners.starting();
繼續跟進starting函數,
public void starting() {
this.initialMulticaster.multicastEvent(
new ApplicationStartingEvent(this.application, this.args));
}
//獲取ApplicationStartingEvent類型的事件後,發布事件
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
}
//繼續跟進invokeListener方法,最後調用ApplicationListener監聽者的onApplicationEvent處理事件
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
.....
}
}
這個後面也會反復遇到,比如listeners.running(context)。
這裏是典型的觀察者模式。
//觀察者:監聽<E extends ApplicationEvent>類型事件
ApplicationListener<E extends ApplicationEvent> extends EventListener
//事件類型:
Event extends SpringApplicationEvent extends ApplicationEvent extends EventObject
//被觀察者:發布事件
EventPublishingRunListener implements SpringApplicationRunListener
SpringApplication根據當前事件Event類型,比如ApplicationStartingEvent,查找到監聽ApplicationStartingEvent的觀察者EventPublishingRunListener,調用觀察者的onApplicationEvent處理事件。
4.環境準備
//根據main函數傳入的參數,創建DefaultApplicationArguments對象
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
//根據掃描到的listeners對象和函數傳入參數,進行環境準備。
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
ApplicationArguments提供運行application的參數,後面會作為一個Bean註入到容器。這裏重點說下prepareEnvironment方法做了些什麽。
private ConfigurableEnvironment prepareEnvironment(
SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
//和listeners.starting一樣的流程
listeners.environmentPrepared(environment);
//上述完成了環境的創建和配置,傳入的參數和資源加載到environment
//綁定環境到SpringApplication
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader())
.convertEnvironmentIfNecessary(environment, deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
這段代碼核心有3個。
- configureEnvironment,用於基本運行環境的配置。
- 發布事件ApplicationEnvironmentPreparedEvent。和發布ApplicationStartingEvent事件的流程一樣。
- 綁定環境到SpringApplication
5.創建ApplicationContext
context = createApplicationContext();
傳說中的IOC容器終於來了。
在實例化context之前,首先需要確定context的類型,這個是根據應用類型確定的。應用類型webApplicationType在構造器已經推斷出來了。
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
//應用為servlet類型的web應用
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
//應用為響應式web應用
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
//應用為非web類型的應用
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);
}
獲取context類型後,進行實例化,這裏根據class類型獲取無參構造器進行實例化。
public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException {
Assert.notNull(clazz, "Class must not be null");
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
//clazz.getDeclaredConstructor()獲取無參的構造器,然後進行實例化
return instantiateClass(clazz.getDeclaredConstructor());
}
catch (NoSuchMethodException ex) {
.......
}
比如web類型為servlet類型,就會實例化org.springframework.boot.web.servlet.context.
AnnotationConfigServletWebServerApplicationContext類型的context。
6.context前置處理階段
private void prepareContext(ConfigurableApplicationContext context,
ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments, Banner printedBanner) {
//關聯環境
context.setEnvironment(environment);
//ApplicationContext預處理,主要配置Bean生成器以及資源加載器
postProcessApplicationContext(context);
//調用初始化器,執行initialize方法,前面set的初始化器終於用上了
applyInitializers(context);
//發布contextPrepared事件,和發布starting事件一樣,不多說
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
//bean, springApplicationArguments,用於獲取啟動application所需的參數
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
//加載打印Banner的Bean
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// Load the sources,根據primarySources加載resource。primarySources:一般為主類的class對象
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
//構造BeanDefinitionLoader並完成定義的Bean的加載
load(context, sources.toArray(new Object[0]));
//發布ApplicationPreparedEvent事件,表示application已準備完成
listeners.contextLoaded(context);
}
7.刷新容器
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
// 註冊一個關閉容器時的鉤子函數,在jvm關閉時調用
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
調用父類AbstractApplicationContext刷新容器的操作,具體的還沒看。
@Override
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();
}
......
}
8.後置操作,調用Runners
後置操作,就是在容器完成刷新後,依次調用註冊的Runners,還可以通過@Order註解設置各runner的執行順序。
Runner可以通過實現ApplicationRunner或者CommandLineRunner接口。
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);
}
}
}
根據源碼可知,runners收集從容器獲取的ApplicationRunner和CommandLineRunner類型的Bean,然後依次執行。
9.發布ApplicationReadyEvent事件
listeners.running(context);
應用啟動完成,可以對外提供服務了,在這裏發布ApplicationReadyEvent事件。流程還是和starting時一樣。
SpringBoot應用啟動過程分析