Spring应用上下文刷新过程
前言
当我们在使用Spring进行应用程序开发时,不管是Spring mvc,还是Spring Boot,Spring应用上下文刷新过程是一个非常重要的概念。在应用程序启动时,Spring会加载并初始化应用程序上下文,将所有配置的bean加载到内存中,然后将它们注入到应用程序中。
本篇通过源码的解读,介绍Spring应用上下文刷新过程的源码实现,帮助读者更好地理解Spring框架的核心机制。
刷新主流程
先贴张图大图:
Spring应用上下文对应的核心api是:org.springframework.context.support.AbstractApplicationContext#refresh
@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.
// 第二步、创建底层IoC容器beanFactory,并返回
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 第三步、beanFactory的准备阶段
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 第四步、beanFactory的后置处理,空方法,由子类覆盖实现内容(以继承的方式进行扩展)。
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 第五步、调用beanFactory的后置处理器(实现BeanFactoryPostProcessors的bean)
// 借助PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors按序调用(PriorityOrdered -> Ordered -> noOrdered)
// 一类是BeanDefinitionRegistryPostProcessor(继承BeanFactoryPostProcessor接口)的注册后置处理器,另一类是BeanFactoryPostProcessor的常规后置处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 第六步、注册BeanPostProcessor bean到beanFactory(AbstractBeanFactory#beanPostProcessors)中,借助PostProcessorRegistrationDelegate#registerBeanPostProcessors
registerBeanPostProcessors(beanFactory);
// 第七步、创建部分Spring内建单例对象,包括下面两个方法
// Initialize message source for this context.
// 初始化内建bean 国际化MessageSource,特定bean的名称:AbstractApplicationContext#MESSAGE_SOURCE_BEAN_NAME
initMessageSource();
// Initialize event multicaster for this context.
// 初始化内建bean 事件广播器,特定bean名称:AbstractApplicationContext#APPLICATION_EVENT_MULTICASTER_BEAN_NAME,默认实现:SimpleApplicationEventMulticaster
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 第八步、当应用上下文刷新,空方法,由子类实现,目前的实现都是web application,没有非web的。可以自行扩展
onRefresh();
// Check for listener beans and register them.
// 第九步、注册事件监听器(第1步是将容器中的事件监听器bean加入到底层的广播器中;第2步是关联bean名称到底层广播器中;第3步是广播早期的事件)
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
// 第十步、完成BeanFactory初始化,主要|重要:初始化非延迟单例beans,包括依赖注入
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 第十一步、最后一步,调用LifecycleProcessor的onFresh方法(可以扩展,自定义同名bean)及发布ContextRefreshedEvent事件
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();
}
}
}
步骤源码
接下来看看refresh每一步的能力
第一步、应用上下文准备阶段
// Prepare this context for refreshing.
// 应用上下文准备阶段
prepareRefresh();
/**
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
// Switch to active.
// 启动时间
this.startupDate = System.currentTimeMillis();
// 应用启动状态位修改
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
}
// Initialize any placeholder property sources in the context environment.
// 初始化属性配置environment,此方法是空实现
// 由子类扩展(主要初始化Environment及初始化PropertySource)
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
// 可以临时存储事件监听器,在refresh上下文之前添加的事件监听器(earlyApplicationListeners其它地方没有再用到了,应该是为了重复refresh时临时存储下)
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
// earlyApplicationListeners不为空时,重置applicationListeners
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 早期事件临时存储,用于在某些场景如BeanPostProcessor中发布事件的话,此时ApplicationEventMulticaster(发布事件的底层实现)还未初始化,等初始化后multicaster
// 再发布earlyApplicationEvents中记录的事件
this.earlyApplicationEvents = new LinkedHashSet<>();
}
第一步主要是准备上下文的刷新,设置启动时间和激活状态,另外也会初始化属性资源及外部化配置类。
有一个点需要注意,earlyApplicationEvents变量,是一个用来存储早期事件的数据结构。后续等发布事件的底层实现实例化后,再基于此进行事件发布。
第二步、创建底层IoC容器
这里会创建默认的IoC容器DefaultListableBeanFactory。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新(销毁当前再增新的)spring应用上下文底层BeanFactory
refreshBeanFactory();
// 返回beanFactory
return getBeanFactory();
}
1、refreshBeanFactory是一个抽象方法,由子类实现,目前有两个实现
第一个:org.springframework.context.support.GenericApplicationContext#refreshBeanFactory
@Override
protected final void refreshBeanFactory() throws IllegalStateException {
// cas refreshed标识
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}
第二个:org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory
// 存在BeanFactory时,先进行销毁(销毁容器中所有的bean),再关闭
if (hasBeanFactory()) {
destroyBeans();
// 关闭,设置serializationId置为null,beanFactory本身置为null
closeBeanFactory();
}
try {
// 创建beanFactory(DefaultListableBeanFactory类)
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 将应用上下文的id设置给beanFactory的序列号id上
beanFactory.setSerializationId(getId());
// 设置allowBeanDefinitionOverriding(bean定义覆盖)与allowCircularReferences(循环依赖)
customizeBeanFactory(beanFactory);
// 重点部分:加载配置的beanDefinition,有几种实现,如xml、注解
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
不管是哪个实现,创建的都是 new DefaultListableBeanFactory(); bean工厂。
2、getBeanFactory()也是一个抽象的方法,两个实现同上,不过都是返回创建的beanFactory。
第三步、beanFactory的准备阶段
// Prepare the bean factory for use in this context.
// beanFactory的准备阶段
prepareBeanFactory(beanFactory);
org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 将applicationContext的classLoader传到beanFactory
beanFactory.setBeanClassLoader(getClassLoader());
// 设置bean表达式处理器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 添加PropertyEditorRegistrar实现
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 配置Aware接口回调的实现(ApplicationContextAwareProcessor)
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
/*
* 忽略Aware回调接口作为依赖注入接口,不关心这些Aware接口,只关心其回调回来的对象
* 因为就算autowire注入了这些接口(这些接口都继承Aware),还是得不到对应的对象
* (例如,注入EnvironmentAware没有意义,它不能得到Environment)
* 可以看下ApplicationContextAwareProcessor#postProcessBeforeInitialization,在bean实例化后调用,
* 例如实现了EnvironmentAware接口,则回调对应的set方法完成注入Environment。
*
*/
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 重要,依赖注入和依赖查找最重要的一个区别,注册4个特殊的bean对象
// 在其它bean进行依赖注入时,会调用DefaultListableBeanFactory#resolveDependency方法进行特殊获取
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 添加bean后置处理BeanPostProcessor(ApplicationListenerDetector),用于判断事件bean(是单例则将Listener添加到上下文)
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
// Register default environment beans.
/*
注册单例对象,environment、system-properties-bean-name、os环境变量
*/
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}
该步主要做了3件事:
第1是忽略Aware回调接口注入;
第2注册了4个特殊的对象(内建依赖,不允许被依赖查询,只允许被依赖注入);
第3是注册了事件监听器的后置处理器ApplicationListenerDetector实现,用于判断事件bean(是单例则将Listener添加到上下文)。
第四步、beanFactory的后置处理(以继承的方式进行扩展)
空方法,由子类覆盖实现内容,完成后置处理
postProcessBeanFactory(beanFactory);
/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
*/
// org.springframework.context.support.AbstractApplicationContext#postProcessBeanFactory
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
第五步、调用beanFactory的后置处理器
这一步说的后置处理器主要指实现BeanFactoryPostProcessors接口的bean
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 调用beanFactory的后置处理器(all registered BeanFactoryPostProcessor beans)
// getBeanFactoryPostProcessors()获取通过上下文Add的beanFactoryPostProcessor
// 借助PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors按序调用(PriorityOrdered -> Ordered -> noOrdered)
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
继续看下org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory, List<BeanFactoryPostProcessor>)
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 记录处理过的bean
Set<String> processedBeans = new HashSet<>();
// Spring有一个默认的ConfigurableListableBeanFactory实现DefaultListableBeanFactory,实现了BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 常规的BeanFactoryPostProcessor bean
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// BeanDefinitionRegistryPostProcessor的bean
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 如果隶属BeanDefinitionRegistryPostProcessor的bean,则加入到registryProcessors中并执行postProcessBeanDefinitionRegistry方法
// 否则加入常规BeanFactoryPostProcessor集合regularPostProcessors中
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
//回调postProcessBeanDefinitionRegistry
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// 临时存储当前处理的BeanDefinitionRegistryPostProcessor(PriorityOrdered -> Ordered -> Other)
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
/*
查询并处理实现了PriorityOrdered的BeanDefinitionRegistryPostProcessor
*/
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 借助OrderComparator排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 循环调用postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
/*
查询并处理实现了Ordered的BeanDefinitionRegistryPostProcessor
*/
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
// 多一个条件!processedBeans.contains(ppName)主要是PriorityOrdered接口继承了Ordered,会把实现了PriorityOrdered的bean也过滤出来
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 借助OrderComparator排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 循环调用postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
/*
查询并处理其它(未实现PriorityOrdered和Ordered)的BeanDefinitionRegistryPostProcessor
*/
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
// 借助OrderComparator排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
// 循环调用postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 调用postProcessBeanFactory方法(BeanFactoryPostProcess的单方法),上面调用的BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
// beanFactory不属于BeanDefinitionRegistry的情况,直接循环调用参数beanFactoryPostProcessors的postProcessBeanFactory
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 从beanDefinition中获取BeanFactoryPostProcessor类型的bean名称
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
/*
通过beanFactory查询BeanFactoryPostProcessor bean,然后分priorityOrdered、ordered、nonOrdered三种情况依次分别处理
processedBeans会判断,如果上面已经处理过了就跳过,因为beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class,)
会拿到BeanDefinitionRegistryPostProcessor类型的bean.(BeanDefinitionRegistryPostProcessor 实现了 BeanFactoryPostProcessor)
*/
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
/*
依次执行priorityOrderedPostProcessors、orderedPostProcessorNames、nonOrderedPostProcessorNames对应bean的postProcessorBeanFactory方法
有点奇怪,priorityOrderedPostProcessors在上面循环时已经拿到BeanFactoryPostProcessor类型,其它两个确是String,然后又在下面循环getBean!
其实在getBean的时候会实例化、初始化,所以priorityOrdered的bean先实例化、再ordered、再nonOrdered
*/
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// 处理完清除一些元数据缓存
beanFactory.clearMetadataCache();
}
该方法说明了一共有两类beanFactory后置处理器的实现bean需要处理。
一类是BeanDefinitionRegistryPostProcessor(继承BeanFactoryPostProcessor接口)的注册后置处理器,先调用BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry,再调用BeanFactoryPostProcess#postProcessBeanFactory;
另一类是BeanFactoryPostProcessor的常规后置处理器,调用BeanFactoryPostProcess#postProcessBeanFactory。
不过不管哪一类,都会按照实现priorityOrdered、ordered、nonOrdered三种情况依次分别处理(借助OrderComparator排序完成排序)。
该步也会通过ConfigurationClassPostProcessor解析配置类,完成对应回调,包括注解:@PropertySource、@ComponentScan、@Import、@ImportResource、@Bean。
第六步、注册BeanPostProcessor bean到beanFactory
该步主要注册BeanPostProcessor bean到beanFactory(AbstractBeanFactory#beanPostProcessors属性)中,借助PostProcessorRegistrationDelegate#registerBeanPostProcessors
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 先根据类型获取所有BeanPostProcessor的beanDefinitionName(这里查询的是beanDefinition,可能还没有实例化)
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
/*
遍历postProcessorNames,将BeanPostProcessor bean加入到下面4个集合中(前2个是BeanPostProcessor类型、后2个是String类型,涉及实例化时间)
*/
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// internalPostProcessors 记录BeanPostProcessor bean如果是MergedBeanDefinitionPostProcessor的情况
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
// 如果BeanPostProcessor同时也是一个MergedBeanDefinitionPostProcessor的话
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
/*
首先排序进行(排序实现类OrderComparator),然后注册到beanFactory#beanPostProcessors有序集合中,依次PriorityOrdered、Ordered、nonOrdered
*/
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
// 获取bean,会进行bean的实例化、初始化等操作
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Finally, re-register all internal BeanPostProcessors.
// 排序内部BeanPostProcessors,重新注册
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
// 重新(beanFactory的prepare阶段add过)注册ApplicationListenerDetector,用于检测内部Bean是否实现了ApplicationListener接口,并将其注册为事件监听器
// 将ApplicationListenerDetector bean移动到处理器链的末端,即先移除再add到有序集合
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
这里注意下,通过beanFactory.getBeanNamesForType(BeanPostProcessor.class,true,false),查询的是beanDefinition;期间进行getBean调用时创建对应的BeanPostProcessor实例。
这些BeanPostProcessor bean的实例方法,会在后面容器创建任何bean的过程中被应用。
这些BeanPostProcessor bean是通过priorityOrdered、ordered、nonOrdered依次进行创建与注册。
第七步、创建部分Spring内部单例对象
包括国际化MessageSource 和 事件广播器SimpleApplicationEventMulticaster
// 初始化内建bean 国际化MessageSource,特定bean的名称:AbstractApplicationContext#MESSAGE_SOURCE_BEAN_NAME
initMessageSource();
// Initialize event multicaster for this context.
// 初始化内建bean 事件广播器,特定bean名称:AbstractApplicationContext#APPLICATION_EVENT_MULTICASTER_BEAN_NAME,默认实现:SimpleApplicationEventMulticaster
initApplicationEventMulticaster();
第八步、当应用上下文刷新
// Initialize other special beans in specific context subclasses.
// 当应用上下文刷新,空方法,由子类实现,目前的实现都是web application,没有非web的。可以自行扩展
onRefresh();
第九步、注册事件监听器
registerListeners();
包括3步,
第1步是将容器中的事件监听器bean加入到底层的广播器中;
第2步是关联Bean名称到底层广播器中;
第3步是广播早期的事件,也是比较重要的一步,发布在initApplicationEventMulticaster被调用之前的事件。
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// Register statically specified listeners first.
// 第1步、将容器中的监听器注册到底层广播器中
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
// 第2步、获取beanDefinition中的事件监听器bean名称数组加入到底层广播器中
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
// 第3步、重要,广播早期事件。有可能在initApplicationEventMulticaster之前发布了事件,例如在beanPostProcessor的回调中发布了事件,earlyApplicationEvents记录的就是早期的事件
// 具体可以看AbstractApplicationContext#publishEvent(Object, ResolvableType)方法,由使用到该集合
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
第十步、完成BeanFactory初始化
该步有个很重要的点,就是初始化非延迟单例beans,包括依赖注入。
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 初始化特定的bean conversionService,用于类型转换
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// beanDefinition查询LoadTimeWeaverAware进行初始化
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
// factory的tempClassLoader置null
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 缓存beanDefinition名称,不希望被改变,beanDefinitionNames-》frozenBeanDefinitionNames
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 重要的步骤:实例化、所有的非懒加载的beanDefinition,使用的默认实现DefaultListableBeanFactory
beanFactory.preInstantiateSingletons();
}
看下beanFactory.preInstantiateSingletons();方法调用,如下:
// org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
// 触发初始化所有非懒加载单例bean
for (String beanName : beanNames) {
// 返回RootBeanDefinition。如果bean是配置了parent,则递归合并parent的属性到当前的bean中,值得注意的是不管是否存在parent,都会包装成RootBeanDefinition
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 几个条件同时满足,非抽象、单例、非懒加载
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
// 如果实现了FactoryBean,则是通过getObject的方式获取实例化对象
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
// 创建bean
getBean(beanName);
}
}
}
// Trigger post-initialization callback for all applicable beans...
// 触发后置处理,当bean初始化后,后置处理器是指实现了SmartInitializingSingleton接口的的bean,如果存在则调用其afterSingletonsInstantiated方法,
// 此时的bean一定是初始化完成的状态了,是在上面getBean后调用的
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
// 后置处理
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
至此,Spring应用上下文基本上启动完成,还差最后一步。
第十一步、通知
最后一步,完成上下文Refresh,调用LifecycleProcessor的onFresh方法(可以扩展,自定义同名bean)及发布ContextRefreshedEvent事件
/**
* Finish the refresh of this context, invoking the LifecycleProcessor's
* onRefresh() method and publishing the
* {@link org.springframework.context.event.ContextRefreshedEvent}.
*/
protected void finishRefresh() {
// Clear context-level resource caches (such as ASM metadata from scanning).
// 清除资源加载时的内存缓存resourceCaches
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 获取LifecycleProcessor bean(实现Lifecycle),如果不存在则初始化默认的DefaultLifecycleProcessor
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
// 调用生命周期函数onRefresh
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 发布上下文刷新事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
如果应用中添加了Spring应用上下文刷新完成的事件监听器,便会在此时触发回调,添加监听器方式如下:
// 方式一(注册该类)
static class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
println("MyApplicationListener - 接收到 Spring 事件:" + event);
}
}
// 方式二
@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {
println("@EventListener(onApplicationEvent) - 接收到 Spring ContextRefreshedEvent");
}
@EventListener 由 Spring内建beanDefinition EventListenerMethodProcessor实现,后续有机会再展开。
总结
通过对Spring应用上下文刷新整个流程的了解,这会对Spring应用包括SpringBoot启动都会有比较大的帮助,我们知道有一些BeanFacatory及Bean的后置处理器可以帮助我们对bean的实例化、初始化时进行自定义扩展。由于篇幅有限,里面有很多步骤都没有深入探讨,后续有机会再展开。
学习Spring有个小建议,不推荐一上来就debug一步一步的跟踪,很容易就会被绕进去,更推荐对每个点进行依次研究,如BeanFactory后置处理、Bean生命周期、事件、资源管理、国际化、类型转换等等,从点到面进行学习,最后再看整体的实现就会更清晰。