Spring 源码分析(一)IOC 容器总览与 refresh() 全景
本文基于 Spring Framework 6.2.x 源码编写,源码为开源项目 spring-projects/spring-framework(Apache 2.0 协议),文中引用均为学习目的的片段摘录,版权归原项目作者所有。
上一阶段的《SpringMVC 6+源码分析》系列已经完结,十一篇拆下来会发现一个很有意思的规律:DispatcherServlet、HandlerAdapter、@ControllerAdvice、消息转换器......这些我们逐个分析过的组件,本质上都是 Spring 容器里的 Bean,它们的注册、依赖注入、生命周期,全都是地底下那台 IOC 容器一手包办的。容器自己是怎么运转的?这个新系列我们就回到地基,把 Spring Framework 最核心的这台发动机拆开看看。
本文作为《Spring 源码分析》的开篇,先解决三个问题:BeanFactory 和 ApplicationContext 到底是什么关系;AnnotationConfigApplicationContext 构造器里做的三件事;以及逐段精读 AbstractApplicationContext#refresh()------它是整个容器的启动主线,后面每一篇的内容,都是这条主线上某一步的展开。
一、概述
先说清楚 IOC 是什么。IOC(Inversion of Control,控制反转)指的是对象的创建权和装配权从我们手里反转给了容器:我们不再 new UserService() 然后手动把 Dao 塞进去,而是把"要哪些对象、依赖什么"描述成 BeanDefinition (可以理解为图纸)交给容器,容器在启动时按图纸批量生产对象、自动接线。所以容器要干的事其实就是两大块:管图纸(BeanDefinition 的注册与解析),管生产(Bean 的实例化、依赖注入与生命周期)。
Spring 里能"管图纸、管生产"的接口有两个层次:最底层的 BeanFactory 和功能完整的 ApplicationContext。用一个表格对比:
| 维度 | BeanFactory | ApplicationContext |
|---|---|---|
| 定位 | 最底层的容器接口,只提供 Bean 的取用能力 | 功能完整的容器门面,内部持有一个 BeanFactory |
| Bean 实例化时机 | 默认等 getBean() 时才实例化(懒) |
refresh() 时预实例化全部非懒加载单例 |
| 国际化消息 | 不支持 | 继承 MessageSource,支持 getMessage() |
| 事件发布 | 不支持 | 继承 ApplicationEventPublisher |
| 环境与 Profile | 不支持 | 继承 EnvironmentCapable,支持 Environment |
| 资源加载 | 不支持 | 继承 ResourcePatternResolver,支持 Ant 风格路径 |
| 后置处理器 | 需要手动注册、手动执行 | refresh() 自动识别并按顺序执行 |
| 典型实现 | DefaultListableBeanFactory |
AnnotationConfigApplicationContext(以及 SpringBoot 里各种各样的 XxxApplicationContext) |
一句话概括两者的关系:ApplicationContext 继承了 BeanFactory 的全部取用能力,再叠加国际化、事件、环境、资源这些"企业级"功能;而它真正的容器职能,是委托给内部组合的那个 DefaultListableBeanFactory 完成的。后面 2.2 节看源码就能证实这一点。
这个系列的源码主线,就是 AbstractApplicationContext#refresh() 这一个方法。习惯上把它拆成十三步,用一张图标注出来(这张图也是本系列的"地图",后续每篇文章都会回到它上面对号入座):

二、容器体系
2.1 BeanFactory 接口族
先看底层。BeanFactory 是整个容器体系的最顶端接口,只定义了 getBean、isTypeMatch、getBeanProvider 这些"取用"方法。在它下面长出了一棵接口树,三个最重要的分支:
java
public interface ListableBeanFactory extends BeanFactory {
/**
* Check if this bean factory contains a bean definition with the given name.
*/
boolean containsBeanDefinition(String beanName);
/**
* Return the number of beans defined in the factory.
*/
int getBeanDefinitionCount();
/**
* Return the names of all beans defined in this factory.
*/
String[] getBeanDefinitionNames();
// ...(略)按类型批量查找的方法:getBeanNamesForType、getBeansOfType、getBeanProvider 等
ListableBeanFactory 的关键字是"可枚举":它让容器不再只能按名字一个一个捞 Bean,而是能列出全部 BeanDefinition、按类型批量查找。javadoc 里还专门提醒了一句:除了 getBeanDefinitionCount 和 containsBeanDefinition,这个接口的方法不建议频繁调用,实现可能很慢------平时排查问题时拿它打一打日志没问题,业务代码里要克制。
java
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
/**
* Scope identifier for the standard singleton scope: {@value}.
* <p>Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_SINGLETON = "singleton";
/**
* Scope identifier for the standard prototype scope: {@value}.
* <p>Custom scopes can be added via {@code registerScope}.
* @see #registerScope
*/
String SCOPE_PROTOTYPE = "prototype";
// ...(略)setParentBeanFactory、setBeanClassLoader、setBeanExpressionResolver、
// addBeanPostProcessor、setConversionService、registerScope 等一系列配置方法
ConfigurableBeanFactory 则是工厂的"配置面":类加载器、作用域常量、BeanPostProcessor 的注册口、类型转换、SpEL 表达式解析器,全从这里进出。注意它同时继承了 HierarchicalBeanFactory(父子容器层级,核心就两个方法 getParentBeanFactory() 和 containsLocalBean())和 SingletonBeanRegistry(手动注册单例的入口),javadoc 里也明说了:这个接口不是给业务代码用的,是框架内部的"插线板"。
把这条接口树一路合体,最后落到一个实现类上:
java
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
// ...
/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
/** Map from bean name to merged BeanDefinitionHolder. */
private final Map<String, BeanDefinitionHolder> mergedBeanDefinitionHolders = new ConcurrentHashMap<>(256);
/** Map of singleton and non-singleton bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
/** Map of singleton-only bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
/** List of bean definition names, in registration order. */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
// ...(略)resolvableDependencies、manualSingletonNames、configurationFrozen 等字段
DefaultListableBeanFactory 就是那个"既管图纸又管生产"的最终实现:ConfigurableListableBeanFactory(可配置 + 可枚举的合体)加上 BeanDefinitionRegistry(注册表入口)。核心字段一眼扫过去就明白了------所谓容器,平时就是一个 beanDefinitionMap:Bean 名字到图纸对象的映射 ,其余的 map 都是加速按类型查找和合并元数据的缓存。另外它还多了一个 BeanDefinitionRegistry 接口,任何"读取器"(XML 的 XmlBeanDefinitionReader、注解的 AnnotatedBeanDefinitionReader)都通过这个接口把图纸塞进来。
用表格整理一下这几个核心接口的分工:
| 接口 | 关键能力 | 代表方法 |
|---|---|---|
| BeanFactory | 取用单个 Bean | getBean、getBeanProvider、isTypeMatch |
| ListableBeanFactory | 枚举图纸、按类型批量查 | getBeanDefinitionNames、getBeansOfType |
| HierarchicalBeanFactory | 父子容器层级 | getParentBeanFactory、containsLocalBean |
| ConfigurableBeanFactory | 工厂的可配置面 | addBeanPostProcessor、registerScope、setBeanClassLoader |
| ConfigurableListableBeanFactory | 前几个合体,可预实例化 | preInstantiateSingletons |
| BeanDefinitionRegistry | 注册表写入口 | registerBeanDefinition、removeBeanDefinition |
2.2 ApplicationContext:继承 + 组合
看完底层,再往上看 ApplicationContext 这一层。它的接口声明非常直白:
java
public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
/**
* Return the unique id of this application context.
*/
@Nullable
String getId();
// ...(略)getApplicationName、getDisplayName、getStartupDate、getParent 等元信息方法
一个 extends 带了六个接口,javadoc 里也逐条列了它提供什么能力:Bean 工厂方法(继承自 ListableBeanFactory)、通用资源加载(继承自 ResourceLoader------通过父接口链带入)、事件发布、国际化消息、父子上下文继承。这就是开头表格里那一长串"ApplicationContext 多出来的功能"的出处:全靠继承。
但注意一个容易忽略的细节:这些能力光继承接口是不够的,接口背后要有实现支撑。AbstractApplicationContext 里是用组合字段把它们落地的:
java
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
// ...
/** Environment used by this context. */
@Nullable
private ConfigurableEnvironment environment;
/** ResourcePatternResolver used by this context. */
private final ResourcePatternResolver resourcePatternResolver;
/** Helper class used in event publishing. */
@Nullable
private ApplicationEventMulticaster applicationEventMulticaster;
// ...
也就是说:接口上继承(Environment、事件发布、资源模式解析),实现上组合 ------environment 字段、resourcePatternResolver 字段、applicationEventMulticaster 字段分别扛起了这三块能力的落地。注意 AbstractApplicationContext 自己还继承了 DefaultResourceLoader,所以"单个资源加载"是靠继承来的,"Ant 模式批量加载"才是靠组合的 PathMatchingResourcePatternResolver。
把继承体系画成类图(这个图建议存下来,后面翻源码迷路的时候回来对坐标):

从图上还能看到一条完整的实现链:AnnotationConfigApplicationContext → GenericApplicationContext → AbstractApplicationContext → ConfigurableApplicationContext 接口 → ApplicationContext 接口。而 GenericApplicationContext 里组合的正是 2.1 节那个 DefaultListableBeanFactory------门面和引擎在这里接上了。
2.3 AnnotationConfigApplicationContext 构造器里做了什么
日常纯注解开发里,new AnnotationConfigApplicationContext(AppConfig.class) 这一行就是容器的全部启动过程。看这个类的源码,其实非常短:
java
public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
private final AnnotatedBeanDefinitionReader reader;
private final ClassPathBeanDefinitionScanner scanner;
/**
* Create a new AnnotationConfigApplicationContext that needs to be populated
* through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
*/
public AnnotationConfigApplicationContext() {
StartupStep createAnnotatedBeanDefReader = getApplicationStartup().start("spring.context.annotated-bean-reader.create");
this.reader = new AnnotatedBeanDefinitionReader(this);
createAnnotatedBeanDefReader.end();
this.scanner = new ClassPathBeanDefinitionScanner(this);
}
// ...(略)传入外部 DefaultListableBeanFactory 的构造器
/**
* Create a new AnnotationConfigApplicationContext, deriving bean definitions
* from the given component classes and automatically refreshing the context.
* @param componentClasses one or more component classes — for example,
* {@link Configuration @Configuration} classes
*/
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses);
refresh();
}
/**
* Create a new AnnotationConfigApplicationContext, scanning for components
* in the given packages, registering bean definitions for those components,
* and automatically refreshing the context.
* @param basePackages the base packages to scan for component classes
*/
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}
// ...(略)registerBean、setEnvironment 等方法
最常用的构造器就三行,对应三个阶段,可以叫它构造器三部曲:
第一步 this() 。无参构造器先被调用,这里有两件事。第一件是隐式的:this() 会一路走到父类 GenericApplicationContext 的无参构造器------
java
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {
private final DefaultListableBeanFactory beanFactory;
@Nullable
private ResourceLoader resourceLoader;
private boolean customClassLoader = false;
private final AtomicBoolean refreshed = new AtomicBoolean();
/**
* Create a new GenericApplicationContext.
*/
public GenericApplicationContext() {
this.beanFactory = new DefaultListableBeanFactory();
}
内部工厂在这一刻就诞生了 。GenericApplicationContext 的 javadoc 里特别强调过:和其他每次 refresh 都新造一个内部 BeanFactory 的实现不同,这个内部工厂从构造一开始就存在,所以你可以随时往里注册 BeanDefinition;相应地,它的 refresh() 只能调用一次(refreshed 这个 AtomicBoolean 字段就是干这个的)。第二件事是显式的:创建 AnnotatedBeanDefinitionReader,而它的构造器最后一行是关键------
java
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
Assert.notNull(environment, "Environment must not be null");
this.registry = registry;
this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
// 向注册表里注册一批内置的基础设施 BeanDefinition
AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
}
AnnotationConfigUtils.registerAnnotationConfigProcessors() 会往刚出生的工厂里塞一批内置的基础设施 BeanDefinition ,其中最重要的一个就是 internalConfigurationAnnotationProcessor,对应 ConfigurationClassPostProcessor------配置类解析的总指挥。此时它们只是"图纸"被注册,还没有实例化(classpath 上有哪些可选库会影响这个名单的具体数量,以 ConfigurationClassPostProcessor 为首这一点不变)。
第二步 register(componentClasses) 。把我们传进来的配置类注册成 BeanDefinition。注意措辞:只是注册图纸,不实例化。
java
@Override
public void register(Class<?>... componentClasses) {
Assert.notEmpty(componentClasses, "At least one component class must be specified");
StartupStep registerComponentClass = getApplicationStartup().start("spring.context.component-classes.register")
.tag("classes", () -> Arrays.toString(componentClasses));
this.reader.register(componentClasses);
registerComponentClass.end();
}
reader 内部就是循环调用 registerBean(),把每个配置类包装成一个 AnnotatedGenericBeanDefinition 放进 beanDefinitionMap。至于配置类里面的 @Bean 方法、@ComponentScan 扫描出来的类,此时统统还不知道------它们的解析要等到 refresh() 里 ConfigurationClassPostProcessor 上场,那是本系列(二)的内容。
第三步 refresh()。真正点火,进入三、源码解析过程。
三、源码解析过程:refresh() 全文逐段讲
回顾完体系,接下来看主角。refresh() 定义在 AbstractApplicationContext 里,是典型的模板方法:骨架固定,十几个钩子留给子类。先把全文贴出来(6.2.x 的样子,和网上流传的 5.x 版本已经有两处不一样了):
java
@Override
public void refresh() throws BeansException, IllegalStateException {
this.startupShutdownLock.lock();
try {
this.startupShutdownThread = Thread.currentThread();
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// Prepare this context for refreshing.
// 准备阶段:刷新上下文前的准备
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 让子类刷新内部 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.
// 留给子类的钩子
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
// 执行工厂级后置处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册 Bean 级后置处理器
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
// 国际化消息源
initMessageSource();
// Initialize event multicaster for this context.
// 事件广播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 子类扩展钩子:初始化特殊 Bean
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 (RuntimeException | Error 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 {
contextRefresh.end();
}
}
finally {
this.startupShutdownThread = null;
this.startupShutdownLock.unlock();
}
}
先说两处 6.2.x 才有的变化,避免读者拿着旧版笔记对不上:
- 最外层从
synchronized换成了显式的ReentrantLock(startupShutdownLock) ,并记录了当前启动线程startupShutdownThread。这是为了配合close()侧更精细的关停处理(比如探测启动线程是不是被System.exit卡住了),对单线程启动的应用来说行为没有差别。 resetCommonCaches()不再是独立挂在finally里的第 13 步 ,而是被并进了finishRefresh()(正常路径)和cancelRefresh()(异常路径)。习惯上我们还是按"十三步"来讲,只是老版本里 finally 里的那一步,6.2 起换了个位置。
整个方法的执行时序可以用一张图串起来:

下面按三组逐段精读。
3.1 准备阶段:prepareRefresh、obtainFreshBeanFactory、prepareBeanFactory
3.1.1 prepareRefresh:立旗、验环境
java
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.
// 初始化占位属性源(子类钩子)
initPropertySources();
// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
// 校验标记为必须的属性都能取到
getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners...
// 保存刷新前的监听器,保证重复刷新时能复位
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
// Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
// 收集早期事件,等广播器就绪后再发布
this.earlyApplicationEvents = new LinkedHashSet<>();
}
这一步干的全是"立规矩"的活:记录启动时间、把 active 标志位立起来(此后再想对同一个 context 调 refresh 会直接拒绝);initPropertySources() 是个空方法钩子,Web 环境的子类会在这里把 Servlet 相关的属性源替换进 Environment;validateRequiredProperties() 则是校验环境,比如你标记了某个必须的配置项,缺了就在这里抛异常。最后两个动作是给事件体系做铺垫:备份早期监听器、创建早期事件容器 earlyApplicationEvents ------在广播器还没就绪的窗口期,publishEvent() 发出的事件会先攒在这里,3.2 节的 registerListeners() 里能看到它们什么时候被补发。
3.1.2 obtainFreshBeanFactory:拿内部工厂
java
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
短得不能再短:调子类的 refreshBeanFactory(),再拿回内部工厂。对 AnnotationConfigApplicationContext 这条线来说,工厂在 this() 里就已经创建好了,GenericApplicationContext#refreshBeanFactory() 主要就是给工厂设置 id 并把 refreshed 标志置为 true,宣告"这个上下文已经刷新过,不能再刷第二次"。真正"每刷一次换一个新工厂"的是 XML 那条老线(AbstractRefreshableApplicationContext),两种设计各自适配了各自的使用场景。
3.1.3 prepareBeanFactory:给工厂做标准装配
java
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 让内部工厂使用上下文的类加载器
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 注册能回调 ApplicationContext 相关 Aware 接口的后置处理器
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
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.ignoreDependencyInterface(ApplicationStartupAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 注册几个"可解析依赖":直接注入容器自身的组件
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.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 检测到 LoadTimeWeaver 时做织入准备
if (!NativeDetector.inNativeImage() && 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.
// 注册默认的环境 Bean
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());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}
}
这一步是把"裸工厂"升级成"ApplicationContext 的工厂",四个动作值得展开:
- 基础设施三件套 :类加载器、SpEL 表达式解析器(
#{...}语法的支撑)、属性编辑器注册器。 - Aware 回调的分流 。
ApplicationContextAwareProcessor是一个BeanPostProcessor,专门负责在 Bean 初始化前回调ApplicationContextAware、EnvironmentAware这些接口。与之配套的ignoreDependencyInterface()则把这些 Aware 接口从普通依赖注入 里排除------不然@Autowired EnvironmentAware aware这种注入会走 setter 注入一份,两条路打架。效果就是:Aware 接口只能通过后置处理器回调,不能通过 @Autowired 注入。 - 可解析依赖 :
registerResolvableDependency把BeanFactory、ApplicationContext这四个类型登记成"遇到就注入这个指定对象",这就是为什么 Controller 里可以直接@Autowired ApplicationContext拿到容器------拿到的就是 context 自己,而不是去容器里找一个叫 XxxApplicationContext 的 Bean。 - 环境三件套 + 指标 :
environment、systemProperties、systemEnvironment、applicationStartup四个内置单例注册进工厂,所以getBean(Environment.class)才能拿到值。注意它们走的是registerSingleton()(手动注册的现成对象),不在 BeanDefinition 名单里。
3.2 后置处理阶段:后置处理器与基础设施初始化
3.2.1 postProcessBeanFactory:子类钩子
java
/**
* Modify the application context's internal bean factory after its standard
* initialization. ...
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
空实现,纯钩子。Web 环境的子类(如 SpringBoot 的 ServletWebServerApplicationContext 的父类 GenericWebApplicationContext、AnnotationConfigServletWebServerApplicationContext)会在这里往工厂里塞 Servlet 相关的特殊后置处理器。纯 Java 工程里这一步等于直接过。
3.2.2 invokeBeanFactoryPostProcessors:图纸加工(本系列(二)(三)的主战场)
java
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (for example, through a @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null &&
beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
本体委托给了 PostProcessorRegistrationDelegate。概括一下它的执行规则:先执行 BeanDefinitionRegistryPostProcessor(它自己就是 BeanFactoryPostProcessor 的子接口,多了一个"往注册表里补图纸"的能力),再执行普通的 BeanFactoryPostProcessor;每一类内部又按 PriorityOrdered、Ordered、无排序三档依次执行。
为什么这一步是整个 refresh() 里最重要的步骤之一?因为 ConfigurationClassPostProcessor 就是 BeanDefinitionRegistryPostProcessor 的实现 ------我们在配置类上写的 @ComponentScan、@Bean、@Import、@ImportResource,全在这一步被解析,扫描出来的 BeanDefinition 全在这里被批量注册进 beanDefinitionMap。一句话:调用这一步之前,容器里只有配置类和内置基础设施的图纸;调用完这一步,你的所有业务 Bean 的图纸就全齐了。
这里有两处常见的困惑顺便说清:第一,getBeanFactoryPostProcessors() 里装的是手动 addBeanFactoryPostProcessor() 传进来的处理器 ,它们不作为 Bean 管理、最先执行;第二,后半段又补检测了一次 LoadTimeWeaver,注释写得很清楚------因为 ConfigurationClassPostProcessor 可能刚刚通过 @Bean 方法注册了这个 Bean,所以要再看一眼。这两块展开讲的内容非常多,对应本系列(二)配置类的解析与扫描、(三)BeanFactoryPostProcessor 的执行顺序。
3.2.3 registerBeanPostProcessors:把 Bean 级处理器先请出来
java
/**
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
又是委托给同一个 delegate。注意措辞:invokeBeanFactoryPostProcessors 是"执行",这里是"注册"------把容器里实现了 BeanPostProcessor 的 Bean 提前实例化 出来,登记进工厂的 beanPostProcessors 列表,同样按 PriorityOrdered、Ordered、无排序分三批。javadoc 里那句 "Must be called before any instantiation of application beans" 就是灵魂:业务 Bean 还没开始生产,监工必须先全部到岗 ,否则先生产出来的 Bean 就享受不到后置处理了(@Autowired 注入就是靠 AutowiredAnnotationBeanPostProcessor 干的,它若是迟到,前面的 Bean 就没人接线)。这个处理器体系的细节和注册顺序的坑,贯穿本系列(四)~(六)的 Bean 生命周期部分。
3.2.4 initMessageSource 与 initApplicationEventMulticaster:两个具名基础设施
java
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource hms &&
hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
java
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}
这两个方法长得几乎一模一样,套路完全统一:约定 Bean 名字,容器里有人配就 getBean 拿来用,没人配就 new 一个默认的兜底 。国际化消息源的约定名是 messageSource,没配就注册一个空的 DelegatingMessageSource(保证 getMessage() 不炸);事件广播器的约定名是 applicationEventMulticaster,没配就注册 SimpleApplicationEventMulticaster。这种"具名 Bean 约定"是 ApplicationContext 体系的经典手法,后面的 lifecycleProcessor 也是同款。
3.2.5 onRefresh 与 registerListeners:钩子与监听器就位
java
/**
* Template method which can be overridden to add context-specific refresh work.
* Called on initialization of special beans, before instantiation of singletons.
* <p>This implementation is empty.
* @throws BeansException in case of errors
* @see #refresh()
*/
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
又一个空钩子,但这是十三步里最有存在感的钩子之一:SpringBoot 的 ServletWebServerApplicationContext 就是在这里创建内嵌 Web 服务器的。回到纯 Java 工程,它就是空过。
java
protected void registerListeners() {
// Register statically specified listeners first.
// 先注册手动添加的监听器
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!
// 只拿名字不初始化,业务 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...
// 广播器就绪了,把 prepareRefresh 里攒的早期事件补发出去
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
注意它的克制:只把监听器 Bean 的名字登记进广播器,并不实例化它们 (getBeanNamesForType 第三个参数 allowEagerInit 传的是 false),实例化统一留到下一大步。最后把 3.1.1 攒下来的早期事件补发------earlyApplicationEvents 置 null,代表"攒事件"的窗口期正式关闭。事件与监听器这套机制展开后就是本系列(六)的内容。
3.3 收尾阶段:finishBeanFactoryInitialization、finishRefresh
3.3.1 finishBeanFactoryInitialization:全面开工(本系列(四)~(六)的主战场)
java
@SuppressWarnings("unchecked")
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Mark current thread for singleton instantiation with applied bootstrap locking.
beanFactory.prepareSingletonBootstrap();
// Initialize bootstrap executor for this context.
if (beanFactory.containsBean(BOOTSTRAP_EXECUTOR_BEAN_NAME) &&
beanFactory.isTypeMatch(BOOTSTRAP_EXECUTOR_BEAN_NAME, Executor.class)) {
beanFactory.setBootstrapExecutor(
beanFactory.getBean(BOOTSTRAP_EXECUTOR_BEAN_NAME, Executor.class));
}
// Initialize conversion service for this context.
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));
}
// Call BeanFactoryInitializer beans early to allow for initializing specific other beans early.
String[] initializerNames = beanFactory.getBeanNamesForType(BeanFactoryInitializer.class, false, false);
for (String initializerName : initializerNames) {
beanFactory.getBean(initializerName, BeanFactoryInitializer.class).initialize(beanFactory);
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
try {
beanFactory.getBean(weaverAwareName, LoadTimeWeaverAware.class);
}
catch (BeanNotOfRequiredTypeException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to initialize LoadTimeWeaverAware bean '" + weaverAwareName +
"' due to unexpected type mismatch: " + ex.getMessage());
}
}
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 冻结配置:此后不再允许修改 BeanDefinition 元数据,全部走缓存
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 实例化全部剩余的非懒加载单例
beanFactory.preInstantiateSingletons();
}
refresh() 的重头戏全压在这一步。开头几个 if 是收尾前的小准备:6.2 新增的 prepareSingletonBootstrap() 给单例实例化阶段标记"引导期锁"策略;bootstrapExecutor 和 conversionService 是两个具名 Bean 的提前获取;占位符解析器的兜底逻辑值得看一眼注释------正常情况下 PropertySourcesPlaceholderConfigurer 这类 BeanFactoryPostProcessor 已经注册过解析器,没人注册才补默认的。中间两段是"需要赶在大家前面初始化"的特殊 Bean(BeanFactoryInitializer、LoadTimeWeaverAware)。
最后三行才是正文:临时类加载器退场、freezeConfiguration() 冻结配置 (之后 beanDefinitionMap 的元数据不再允许随意改动,全部走合并缓存),以及最关键的 preInstantiateSingletons() ------遍历全部 BeanDefinition,把所有非懒加载、单例、非抽象的 Bean 逐个 getBean() 生产出来。构造方法、依赖注入、Aware 回调、初始化回调、AOP 代理织入,全发生在这里。这一行代码内部,就是本系列(四)~(六)整整几篇的体量:Bean 的实例化与依赖注入(四)、Aware 与生命周期回调(五)、事件与监听器(六)。
3.3.2 finishRefresh 与 resetCommonCaches:庆典与清扫
java
protected void finishRefresh() {
// Reset common introspection caches in Spring's core infrastructure.
// 清理通用的反射元数据缓存
resetCommonCaches();
// Clear context-level resource caches (such as ASM metadata from scanning).
// 清理上下文级资源缓存(比如扫描用的 ASM 元数据)
clearResourceCaches();
// Initialize lifecycle processor for this context.
// 初始化生命周期处理器
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
// 通知生命周期处理器启动各阶段的 SmartLifecycle
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 发布收官事件
publishEvent(new ContextRefreshedEvent(this));
}
java
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}
开头就先做了一次缓存清扫------这是 6.2 的变动:老版本里 resetCommonCaches() 单独挂在 refresh() 的 finally 里,6.2 起挪到了 finishRefresh() 开头(异常路径则在 cancelRefresh() 里同样清理),清理的对象是 ReflectionUtils、AnnotationUtils、ResolvableType、CachedIntrospectionResults 这四个全局反射缓存,防止启动期缓存的元数据在后续长期运行中变成脏数据或多余占用。随后的主线就是三件事:初始化 lifecycleProcessor(又是具名 Bean 约定)、让实现了 SmartLifecycle 的 Bean 自动启动,最后发布 ContextRefreshedEvent ------所有监听这个事件的 Bean 都在此刻收到"容器就绪"的信号。@PostConstruct 之后还挂着 ApplicationListener<ContextRefreshedEvent> 的应用逻辑,就是从这里触发的。
最后把异常分支看完整。回到 refresh() 全文,catch (RuntimeException | Error) 里只有三个动作:destroyBeans() 把已经创建出来的 单例逐个销毁(注意措辞,没创建完的不欠了)、cancelRefresh() 把 active 复位并清缓存,然后把异常原样抛给调用者。所以容器启动失败不会留下"半死不活"的单例在工厂里挂着,这就是 Spring 容器一致性的保障。最外层的 finally 只做锁的释放------成功也罢、失败也罢,启动流程至此终局。
十三步走完,串一个表格,标出每一步的职责和它们在本系列后续文章里的落点:
| 步骤 | 职责一句话 | 本系列后续落点 |
|---|---|---|
| 1. prepareRefresh | 立活跃标志、验环境、攒早期事件 | --- |
| 2. obtainFreshBeanFactory | 拿到内部 DefaultListableBeanFactory | --- |
| 3. prepareBeanFactory | 标准装配:Aware 分流、可解析依赖、环境 Bean | --- |
| 4. postProcessBeanFactory | 子类扩展钩子 | --- |
| 5. invokeBeanFactoryPostProcessors | 执行工厂级处理器,解析配置类补全图纸 | (二)(三) |
| 6. registerBeanPostProcessors | 提前注册 Bean 级监工 | (四) 起贯穿 |
| 7. initMessageSource | 国际化消息源 | --- |
| 8. initApplicationEventMulticaster | 事件广播器 | (六) |
| 9. onRefresh | 子类特殊 Bean 钩子(Boot 的 Web 服务器在此创建) | --- |
| 10. registerListeners | 登记监听器、补发早期事件 | (六) |
| 11. finishBeanFactoryInitialization | 冻结配置、实例化全部单例 | (四)~(六) |
| 12. finishRefresh | Lifecycle 启动、发布 ContextRefreshedEvent | (六) |
| 13. resetCommonCaches | 反射元数据缓存清理(6.2 起并入 12) | --- |
四、Demo 实战验证
以上流程整理成一个可运行的纯 Maven Java 工程(不依赖 SpringBoot,文末有完整代码地址)。核心代码只有四个文件,pom.xml 只依赖 spring-context:
java
/**
* 业务 Bean:走 @ComponentScan 注册
*/
@Component
public class UserService implements InitializingBean {
public UserService() {
System.out.println("[Constructor] UserService 实例化");
}
@Override
public void afterPropertiesSet() {
System.out.println("[InitializingBean] UserService 初始化完成");
}
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
java
/**
* 配置类:一个 @ComponentScan + 一个 @Bean 方法,覆盖两种注册方式
*/
@Configuration
@ComponentScan(basePackages = "com.example.ioc.service")
public class AppConfig {
@Bean
public Clock systemClock() {
return Clock.systemDefaultZone();
}
}
java
public class DemoApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
System.out.println(userService.sayHello("refresh"));
System.out.println("---- 容器内全部 Bean 名单 ----");
for (String name : context.getBeanDefinitionNames()) {
System.out.println(name);
}
context.close();
}
}
运行输出里能看到清晰的阶段:UserService 实例化 → 初始化完成(发生在 preInstantiateSingletons 阶段)→ Hello, refresh! → 全部 Bean 名单。启动期间重点在下面这些位置打断点,把 3.1~3.3 的源码逐段验证一遍(IDEA 直接按类名 + 方法名定位即可):
| 断点位置 | 观察内容 |
|---|---|
AnnotationConfigApplicationContext(Class<?>...) 构造器的 this() |
Step Into 父类构造器链,确认 GenericApplicationContext 里 beanFactory = new DefaultListableBeanFactory() 先执行 |
AnnotatedBeanDefinitionReader 构造器末行 |
注册完成后查看 beanFactory.beanDefinitionMap,此时只有内置基础设施和后续将出现的配置类图纸 |
AnnotationConfigApplicationContext#register() 结束后 |
beanDefinitionMap 里新增了 appConfig 一个键;@Bean 的 systemClock 和 userService 还没出现 |
AbstractApplicationContext#refresh() 入口 |
查看完整调用栈;观察 startupShutdownLock 加锁 |
prepareRefresh() 结尾 |
active = true、earlyApplicationEvents 为空集合 |
obtainFreshBeanFactory() 返回处 |
beanDefinitionMap 依然没有 userService------业务图纸还没解析 |
PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors 内部 |
观察 ConfigurationClassPostProcessor 执行前后 beanDefinitionMap 的变化:userService、systemClock 都是在这一步才进来的 |
AbstractApplicationContext#registerBeanPostProcessors 结束后 |
beanFactory.beanPostProcessors 列表的组成(Aware 回调、注解注入、监听器探测都在里面) |
DefaultListableBeanFactory#preInstantiateSingletons |
遍历时逐个放行,对照控制台输出看每个 Bean 的构造与初始化时机 |
AbstractApplicationContext#finishRefresh |
观察先执行的 resetCommonCaches()(6.2 的位置变化),以及 ContextRefreshedEvent 的发布 |
其中第五行和第七行是理解"注册 ≠ 解析 ≠ 实例化 "三个阶段的最佳观察点:构造器三部曲只完成了注册,invokeBeanFactoryPostProcessors 完成解析(扫描出全部图纸),preInstantiateSingletons 才开始实例化。很多"容器启动后为什么拿不到 Bean"的疑惑,都能在这张表上找到答案。
最后用一张图把本文的知识点归纳一下:

五、总结
IOC 容器的启动主线就是 AbstractApplicationContext#refresh() 这一个模板方法:前三步准备好工厂,中段把图纸解析完整、把监工注册到位,finishBeanFactoryInitialization 全面开工生产单例,最后发布 ContextRefreshedEvent 收官。本系列后续每一篇,都是这条主线某一层的放大:下一篇我们钻进第五步里最核心的角色------ConfigurationClassPostProcessor,看看配置类的解析与 @ComponentScan 扫描到底是怎么把你的业务图纸注册进容器的。
Demo 完整代码 :Spring/S01-refresh全景/ioc-refresh-demo(Spring Framework 6.2.5 + JDK 17,mvn compile exec:java 启动后按上表逐个断点验证)
专栏往期:
- SpringMVC 6+源码分析(一)初始化流程
- SpringMVC 6+源码分析(二)DispatcherServlet实例化流程 1
- SpringMVC 6+源码分析(三)DispatcherServlet实例化流程 2
- SpringMVC 6+源码分析(四)DispatcherServlet实例化流程 3------HandlerAdapter初始化
- SpringMVC 6+源码分析(五)执行流程
- SpringMVC 6+源码分析(六)参数处理
- SpringMVC 6+源码分析(七)返回值处理
- SpringMVC 6+源码分析(八)拦截器
- SpringMVC 6+源码分析(九)异常处理
- SpringMVC 6+源码分析(十)数据绑定与类型转换
- SpringMVC 6+源码分析(十一)视图渲染与异步请求(收尾篇)
本文为「源码学习」专栏系列文章,转载请注明出处。相互学习,共同进步!