spring版本: 5.0.6
springboot版本: 2.0.2
先祭出一張 spring 容器的核心接口圖:
spring 容器有兩個(gè)核心接口:BeanFactory 和 ApplicationContext,其中 ApplicationContext是 BeanFactory的子類, 這兩個(gè)類生成并管理 spring 容器中的 bean坦弟。但是大多數(shù)情況都是用ApplicationContext作為spring 的容器累魔。 spring mvc和 spring boot 都是通過(guò) applicationContext作為管理 bean 的容器的鞍陨。 其中 spring boot 默認(rèn)使用的是AnnotationConfigServletWebServerApplicationContext(還可以使用AnnotationConfigReactiveWebServerApplicationContext洪燥,有興趣的同學(xué)可以研究一下霉祸,什么情況下會(huì)使用這個(gè)轻姿。)犁珠, spring boot 類似 spring mvc都是 web server, 因此使用" servlet application context"作為默認(rèn)容器十分可以理解傅瞻。AnnotationConfigServletWebServerApplicationContext本身是一個(gè) BeanFactory的派生類,而它的父 context 也會(huì)持有一個(gè) BeanFactory盲憎。
再來(lái)說(shuō)說(shuō)啟動(dòng)過(guò)程:
springboot 的啟動(dòng)入口是 SpringApplication run方法嗅骄,代碼如下:
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
//此處創(chuàng)建 context
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(
SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
//初始化context 的核心邏輯都在這行代碼里。
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
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;
}
再具體分析下 refreshContext的代碼邏輯
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//清除緩存饼疙,并讀取配置文件里的環(huán)境變量
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 此處的 bean factory 是通過(guò)父類GenericApplicationContext 初始化的 DefaultListableBeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 配置 beanFactory溺森, 包括注冊(cè)(第一次) BeanPostProcessor, 設(shè)置 classLoader等等。
// BeanPostProcessor 有兩個(gè)主要的方法:postProcessBeforeInitialization 和 postProcessAfterInitialization 窑眯。
// 這個(gè)兩個(gè)方法分別的執(zhí)行時(shí)期是 bean 初始化之前和初始化之后屏积。具體的執(zhí)行時(shí)期后面會(huì)說(shuō)到
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//為 applicationContext的子類注冊(cè)(第二次)個(gè)性化的 BeanPostProcessor
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//執(zhí)行 context 中注冊(cè)的 BeanFactoryPostProcessor中的postProcessBeanFactory() 方法,BeanFactoryPostProcessor只有這一個(gè)方法
//BeanFactoryPostProcessor 是 bean 屬性處理容器磅甩。即管理 bean工廠中的BeanDefinition,
// BeanDefinition在 spring mvc 中就是 xml 文件中對(duì)應(yīng)的 bean 標(biāo)簽(注意炊林,是標(biāo)簽,而不是真實(shí)的 JAVA BEAN)卷要。
//可以看到渣聚,此處已經(jīng) invoke 了postProcessBeanFactory() 方法。 而 BeanPostProcessor 的方法還沒(méi)有被調(diào)用僧叉,
//所以 BeanFactoryPostProcessor的執(zhí)行是要早于BeanPostProcessor的奕枝。
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//再次注冊(cè)BeanPostProcessor(這已經(jīng)是第三次注冊(cè),
// 第一注冊(cè)的是AbstractApplicationContext中用到的 processor,
// 第二次為ServletWebServerApplicationContext 注冊(cè) processor)瓶堕。
// 這次是為實(shí)際用到的 context注冊(cè) processor(spring boot 即是AnnotationConfigServletWebServerApplicationContext)隘道,
// 并為根據(jù)優(yōu)先級(jí)和 order 排序。
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 實(shí)例化并注冊(cè) MessageSource類郎笆。MessageSource是國(guó)際化相關(guān)的接口
initMessageSource();
// Initialize event multicaster for this context.
//初始化spring 事件廣播器谭梗,ApplicationContext會(huì)通過(guò)廣播器發(fā)送事件,負(fù)責(zé)監(jiān)聽(tīng)廣播器的 listener 會(huì)負(fù)責(zé)處理事件
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 在一些特殊的 ApplicationContext子類中實(shí)例化一些特殊的 bean.
//例如ServletWebServerApplicationContext(AnnotationConfigServletWebServerApplicationContext的父類)會(huì)初始化TomcatWebServer宛蚓,
//并啟動(dòng)這個(gè) server激捏,在 spring boot 工程中,相當(dāng)于啟動(dòng)了整個(gè) spring boot 項(xiàng)目苍息。
onRefresh();
// Check for listener beans and register them.
//為ApplicationEventMulticaster注冊(cè)監(jiān)聽(tīng) listener(ApplicationListener),
//會(huì)有一些默認(rèn)的 listener被注冊(cè)缩幸。例如這是一個(gè) dubbo provider的工程壹置,就會(huì)注冊(cè)DubboBannerApplicationListener
// 同時(shí)也會(huì)有一些自定義的 listener.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//終于到了初始 java bean 的階段竞思, 注意此處只初始化單例的 bean, 并且非懶加載的類(默認(rèn)即非懶加載)。
//雖然此時(shí) java bean已經(jīng)實(shí)例化钞护,但是其依賴自動(dòng)注入的 bean卻不再此時(shí)注入盖喷,而是等到用到的時(shí)候再去獲取,
//所以這里不會(huì)出現(xiàn)循環(huán)依賴的問(wèn)題难咕。
// 一個(gè) spring bean 的初始化過(guò)程如下:
// 1. 執(zhí)行構(gòu)造器
// 2. BeanPostProcessor的postProcessBeforeInitialization方法
// 3. InitializingBean的afterPropertiesSet方法
// 4课梳,@Bean注解的initMethod方法
// 5距辆,BeanPostProcessor的postProcessAfterInitialization方法
// 6,DisposableBean的destroy方法
// 7暮刃,@Bean注解的destroyMethod方法
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//實(shí)例化LifecycleProcessor并執(zhí)行其 onRefresh()方法跨算,刷新上下文,啟動(dòng)一些需要在初始化階段啟動(dòng)的類(實(shí)現(xiàn)了Lifecycle接口的類)
// 發(fā)布ContextRefreshedEvent事件椭懊,這個(gè)應(yīng)該是表示上下文啟動(dòng)完成的事件
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...
//清理單例 bean 的元數(shù)據(jù)緩存诸蚕。
resetCommonCaches();
}
}
}
至此, spring boot的啟動(dòng)過(guò)程就完成了氧猬, 基于篇幅和時(shí)間問(wèn)題背犯。其中還有很多代碼細(xì)節(jié)沒(méi)有仔細(xì)分析,這些就留給未來(lái)吧盅抚。
整個(gè)過(guò)程分析下來(lái)發(fā)現(xiàn)這個(gè)啟動(dòng)過(guò)程會(huì)有幾個(gè)核心接口(應(yīng)該也是 spring 整個(gè) ioc機(jī)制的核心接口)
- BeanFactory
- ApplicationContext
- BeanPostProcessor
- BeanFactoryPostProcessor
- ApplicationEventMulticaster
- BeanDefinition
- LifecycleProcessor
以及每個(gè)接口里面的方法及其執(zhí)行時(shí)序漠魏。
弄清楚每一個(gè)接口的原理和具體使用場(chǎng)景,對(duì)我們使用和理解 spring 至關(guān)重要妄均。