Spring 源码分析(六)循环依赖与三级缓存
本文基于 Spring Framework 6.2.x(Spring Boot 3.4.x 所对应版本)源码编写,源码为开源项目 spring-projects/spring-framework(Apache 2.0 协议),文中引用均为学习目的的片段摘录,版权归原项目作者所有。
上一篇(五)我们走完了 Bean 生命周期的后半段:初始化、销毁,一个单例 Bean 顺理成章地登记进一级缓存,整个流程按部就班。但有一个特殊情况会打断这个"顺利流程"------A 依赖 B,B 又依赖 A。创建 A 要先有 B,创建 B 又要先有 A,鸡生蛋蛋生鸡,Spring 是怎么解开的?答案就是本文的主角:三级缓存。
本文我们拆解 DefaultSingletonBeanRegistry 里的三个 Map,把 AB 循环依赖的完整调用链从头到尾走一遍。
一、概述
1.1 什么是循环依赖
循环依赖(Circular Reference)指两个或多个 Bean 相互持有对方引用,形成闭环。最常见的是两个 Bean 的互相依赖:
java
@Component
public class A {
@Autowired
private B b;
}
@Component
public class B {
@Autowired
private A a;
}
按(四)(五)篇讲的生命周期,一个单例 Bean 要经历 实例化 → 属性填充 → 初始化 三大步。麻烦就出在属性填充上:A 要完成属性填充,必须先拿到 B;而 B 还没创建。于是只能先去创建 B,结果 B 的属性填充又需要 A------此时 A 已经实例化了(构造器已执行,裸对象已存在),只是还没填充属性、没初始化。
关键就一句:A 在"实例化"和"初始化完成"之间,存在一个中间状态------裸对象已经存在,但还不完整。如果别的 Bean 愿意接受这个"半成品"引用,环就能解开。Spring 的三级缓存,本质上就是围绕这个中间状态做的一套"半成品暴露"机制。
用一张图标注出循环依赖处理在整个 Bean 创建流程中的位置(两个关键点:提前暴露在实例化之后、缓存查询在 doGetBean 一进来):

1.2 先抛出一个问题:一级不行吗?两级不行吗?
直觉方案是:实例化完 A 就把它放进缓存,B 创建时从缓存拿。这样一个缓存就够了,为什么 Spring 搞了三个?
问题出在 AOP 代理 上。回顾(五)篇说的:正常情况下,代理对象是在初始化之后 由 BeanPostProcessor 的 postProcessAfterInitialization() 生成的。假设 A 需要 AOP 增强:
- 如果只有一级缓存:B 在 A 还没初始化时来要 A,Spring 只能要么给裸对象(B 里注入的是未经增强的 A,最终容器里却是代理对象,两者不一致),要么提前到实例化后就生成代理(违背了代理在初始化后生成的设计,所有 Bean 都要承担代理提前创建的代价)。
- 如果有二级缓存(成品 + 半成品两个 Map):把"提前生成代理"做成按需的------B 来要的时候,通过工厂生成 A 的早期引用(可能是代理),放进半成品缓存。看起来两级就能跑通?
但 Spring 的选择是:在二级之外再加一层"工厂"缓存 。原因是代理的生成必须委托给 SmartInstantiationAwareBeanPostProcessor(AOP 场景下就是 AbstractAutoProxyCreator),什么时候生成、生成什么样,只有后置处理器知道。所以第三级存的不是对象,而是 ObjectFactory 工厂 ------把"如何生成早期引用"这个决定权延迟到真正有人来要的那一刻,并且保证每个 Bean 的早期引用只生成一次 。3.3 节看到 getEarlyBeanReference() 的源码后,这个设计意图会非常清楚。
至于"如果只有一级缓存"还有个更直接的死结:一旦 B 拿着 A 的半成品引用注入成功、B 自己完成初始化进入一级缓存,此时 A 还是半成品------同一个 Map 里成品和半成品混在一起 ,后续 getBean(A) 可能拿到不完整的 A。成品、半成品、工厂分三个 Map 存,边界才清晰。
1.3 AB 循环依赖的宏观时序
先从 30,000 英尺俯瞰一遍解环过程,细节后面逐段看源码:
getBean("a"):一级缓存没有 a,进入创建流程,把 a 标记为"创建中";- A 实例化完成(裸对象诞生),立刻把一个工厂放进三级缓存兜底;
- A 属性填充,发现依赖 B →
getBean("b"):B 同样实例化、暴露工厂,然后 B 属性填充发现依赖 A →getBean("a"); getSingleton("a")再查缓存:一级没有,但 a 在"创建中"名单里,逐级往下查------三级缓存的工厂被调用,产出 A 的早期引用(必要时此时生成代理),转入二级缓存,返回给 B;- B 注入 A 的引用成功 → B 初始化完成 → B 进入一级缓存;
- 回到 A 的属性填充,B 注入成功 → A 初始化完成 → A 进入一级缓存。环解开。
二、三级缓存拆解
2.1 三个 Map 的定义与注释原文
三级缓存全部定义在 DefaultSingletonBeanRegistry(spring-beans 模块,org.springframework.beans.factory.support 包)里,这个类是整个单例缓存体系的大本营。先看字段定义原文(6.2.x):
java
/** Common lock for singleton creation. */
final Lock singletonLock = new ReentrantLock();
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Creation-time registry of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new ConcurrentHashMap<>(16);
/** Custom callbacks for singleton creation/registration. */
private final Map<String, Consumer<Object>> singletonCallbacks = new ConcurrentHashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = Collections.synchronizedSet(new LinkedHashSet<>(256));
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation = ConcurrentHashMap.newKeySet(16);
逐个解读:
singletonObjects------一级缓存 :javadoc 直白地说这是"单例对象的缓存",存的是成品 ------完整走完生命周期、可以放心对外使用的单例。doGetBean()第一站查的就是它。earlySingletonObjects------二级缓存 :"早期单例对象的缓存",存的是半成品 ------提前暴露出去的早期引用。可能是裸对象本身,也可能是代理(3.3 节详述)。它的定位是车间到仓库的临时中转区:工厂生产出早期引用后先进这里,等 Bean 最终完工进入一级缓存时,这里就被清掉。singletonFactories------三级缓存 :"创建期的单例工厂注册表",存的是ObjectFactory工厂 。注意注释里特意标了 Creation-time------只在创建过程中存在,是三个缓存里生命周期最短的一级。singletonCallbacks是 6.2 新增的"单例创建/注册自定义回调",不属于经典三级缓存体系,本文不展开;singletonsCurrentlyInCreation(创建中名单)虽然不是缓存,却是三级缓存能工作的前提------二级缓存的查询条件就是它,后面 3.1 节会看到。- 另外 6.2 有个值得注意的结构变化:单例创建的全局锁从旧的
synchronized块换成了显式的ReentrantLock(singletonLock),getSingletonMutex()已标记@Deprecated(since = "6.2")。这是 6.2 重构并发创建(lenient creation)的一部分,主流程语义不变,遇到的地方我会顺带说明。
三级缓存的类型结构用类图串一下(含关键的读写方法与两个配置开关):

2.2 每一级的读写时机
| 缓存 | 存什么 | 写入时机 | 读取时机 | 移除时机 |
|---|---|---|---|---|
一级 singletonObjects |
成品单例 | Bean 初始化全部完成后,addSingleton() |
doGetBean() 第一站 / getSingleton(beanName, true) 第一级 |
容器销毁 destroySingleton() |
二级 earlySingletonObjects |
早期引用(裸对象或代理) | 三级缓存的工厂被调用、产出早期引用后(转存) | getSingleton(beanName, true) 第二级(前提:该 Bean 在创建中) |
Bean 完工进一级缓存时;创建失败 removeSingleton() 时 |
三级 singletonFactories |
ObjectFactory 工厂 |
实例化之后、属性填充之前,addSingletonFactory() |
getSingleton(beanName, true) 第三级(仅当 allowEarlyReference = true) |
工厂被调用后立即移除(用完即焚);Bean 完工/失败时一并清除 |
三个规律值得咀嚼:一级只进成品,半成品永远进不去 ;二级的存在让工厂只执行一次 (工厂被调用后就转存二级,第三次起走二级命中);三级是纯粹的"待命"状态,正常流程里大多数 Bean 的工厂从放入到清除都不会被调用一次------只有真的发生了循环依赖,它才有出场机会。
三、源码解析过程
3.1 缓存查询:getSingleton(String, boolean) 的三级递进
回顾完缓存结构,接下来看查询入口。整个故事从 AbstractBeanFactory#doGetBean() 开始,先看它开头几行:
java
String beanName = transformedBeanName(name);
Object beanInstance;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
getSingleton(beanName) 是一级查询的入口,但注意 trace 日志里的那句话:"Returning eagerly cached instance ... a consequence of a circular reference" ------如果查到的实例所属的 Bean 还在创建中,说明此刻正处于一次循环依赖的解环现场,返回的是早期引用。这个 getSingleton(beanName) 最终落到 DefaultSingletonBeanRegistry 的重载方法,全文如下(这是理解三级递进最核心的一段):
java
/**
* Return the (raw) singleton object registered under the given name.
* <p>Checks already instantiated singletons and also allows for an early
* reference to a currently created singleton (resolving a circular reference).
* @param beanName the name of the bean to look for
* @param allowEarlyReference whether early references should be created or not
* @return the registered singleton object, or {@code null} if none found
*/
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock.
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
if (!this.singletonLock.tryLock()) {
// Avoid early singleton inference outside of original creation thread.
return null;
}
try {
// Consistent creation of early reference within full singleton lock.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
// Singleton could have been added or removed in the meantime.
if (this.singletonFactories.remove(beanName) != null) {
this.earlySingletonObjects.put(beanName, singletonObject);
}
else {
singletonObject = this.singletonObjects.get(beanName);
}
}
}
}
}
finally {
this.singletonLock.unlock();
}
}
}
return singletonObject;
}
三级递进的骨架一目了然:一级 singletonObjects → 二级 earlySingletonObjects → 三级 singletonFactories。逐层拆解:
-
第一级,无锁快查 :直接查
singletonObjects,命中就返回。注释写明这是"不开全量单例锁的快速检查"------绝大多数getBean()调用(Bean 早就创建好了)都走这条最快路径。 -
第二级,前提是"创建中" :一级没命中还不够,还要
isSingletonCurrentlyInCreation(beanName)为 true 才继续。这个条件至关重要------只有正在创建中的 Bean,才可能存在合法的早期引用。一个创建完的 Bean 二级缓存里绝不会有它的残留,一个没创建过的 Bean 更不该有。没有这个门槛,缓存语义就乱了。 -
第三级,工厂生产 + 转存二级 :
allowEarlyReference允许时,拿三级缓存里的ObjectFactory,调用getObject()产出早期引用。紧接着两个动作是精髓:this.singletonFactories.remove(beanName)------工厂用完即焚;this.earlySingletonObjects.put(beanName, singletonObject)------产物转存二级。
下一次再有人来要这个 Bean 的早期引用,就会在第二级直接命中,工厂不会执行第二次。这保证了同一个 Bean 的早期引用全容器只有一份------B、C、D 都依赖正在创建的 A 时,它们拿到的是同一个引用。
-
转存的并发保险 :
remove是有返回值的,注释说"Singleton could have been added or removed in the meantime"------如果remove返回 null(说明并发场景下工厂已被别的线程消费或已被清除),就回退到singletonObjects再确认一次。这是 6.2.x 对这段代码加的并发加固。
再注意到 6.2 的一个行为细节:锁的获取用的是 tryLock() 而不是 lock() ,拿不到锁直接 return null,注释写得很清楚------"Avoid early singleton inference outside of original creation thread"(避免在原始创建线程之外推断早期单例)。也就是说,早���引用的生产只发生在持有创建权的那个线程上下文里,其他线程并发来要同一个半成品时,宁可返回 null 也不越权生产。这是 6.2 重构单例锁后的语义收紧,主流程(单线程启动容器)感知不到。
3.2 提前暴露:doCreateBean 的 earlySingletonExposure 条件
查询侧看完了,再看生产侧------三级缓存里的工厂是什么时候放进去的。承接(四)篇贴过的 doCreateBean(),这次聚焦实例化之后的那一段(AbstractAutowireCapableBeanFactory):
java
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException bce && beanName.equals(bce.getBeanName())) {
throw bce;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName, ex.getMessage(), ex);
}
earlySingletonExposure 由三个条件与出来:
mbd.isSingleton():只有单例才有资格,prototype 没有缓存,3.5 节细说;this.allowCircularReferences:全局开关,默认 true。看一眼它的定义与 setter 注释原文:
java
/** Whether to automatically try to resolve circular references between beans. */
private boolean allowCircularReferences = true;
java
/**
* Set whether to allow circular references between beans - and automatically
* try to resolve them.
* <p>Note that circular reference resolution means that one of the involved beans
* will receive a reference to another bean that is not fully initialized yet.
* This can lead to subtle and not-so-subtle side effects on initialization;
* it does work fine for many scenarios, though.
* <p>Default is "true". Turn this off to throw an exception when encountering
* a circular reference, disallowing them completely.
* <p><b>NOTE:</b> It is generally recommended to not rely on circular references
* between your beans. Refactor your application logic to have the two beans
* involved delegate to a third bean that encapsulates their common logic.
*/
public void setAllowCircularReferences(boolean allowCircularReferences) {
this.allowCircularReferences = allowCircularReferences;
}
注意官方注释里两个信息:一是"循环引用解析意味着其中一个 Bean 拿到的是另一个尚未完全初始化 的 Bean 的引用,可能带来微妙或不微妙的副作用";二是末尾的官方态度------** generally recommended to not rely on circular references**,官方建议重构掉循环依赖而不是依赖它。这也是 Spring Boot 从 2.6 开始默认关闭循环依赖解析(需要 spring.main.allow-circular-references=true 显式打开)的注脚。
isSingletonCurrentlyInCreation(beanName):当前 Bean 必须在"创建中"名单里。它是在更外层的getSingleton(String, ObjectFactory)里被beforeSingletonCreation()加进去的。看这个方法的判断逻辑:
java
/**
* Callback before singleton creation.
* <p>The default implementation register the singleton as currently in creation.
* @param beanName the name of the singleton about to be created
* @see #isSingletonCurrentlyInCreation
*/
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
/**
* Callback after singleton creation.
* <p>The default implementation marks the singleton as not in creation anymore.
* @param beanName the name of the singleton that has been created
* @see #isSingletonCurrentlyInCreation
*/
protected void afterSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.remove(beanName)) {
throw new IllegalStateException("Singleton '" + beanName + "' isn't currently in creation");
}
}
singletonsCurrentlyInCreation.add() 返回 false 意味着 add 失败------名单里已经有它了 ,即这个 Bean 已经在被创建的过程中又有人发起了一次创建请求,直接抛 BeanCurrentlyInCreationException。这个方法就是"创建中"名单的守门员:进入创建先登记,重复创建立刻报警(构造器循环依赖就是死在这里,3.5 节细说)。
回看 addSingletonFactory() 那一行,重点有两个。其一,时机 :实例化之后、属性填充之前------此刻裸对象已成型,但属性还是空的。其二,放进去的是 Lambda 工厂 :() -> getEarlyBeanReference(beanName, mbd, bean),bean 是刚实例化的裸对象的引用。工厂不立刻执行,只是"待命"。
工厂最终落地到 DefaultSingletonBeanRegistry 的这两个方法里,与成品的登记方法对照着看:
java
/**
* Add the given singleton object to the singleton registry.
* <p>To be called for exposure of freshly registered/created singletons.
* @param beanName the name of the bean
* @param singletonObject the singleton object
*/
protected void addSingleton(String beanName, Object singletonObject) {
Object oldObject = this.singletonObjects.putIfAbsent(beanName, singletonObject);
if (oldObject != null) {
throw new IllegalStateException("Could not register object [" + singletonObject +
"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
}
this.singletonFactories.remove(beanName);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
Consumer<Object> callback = this.singletonCallbacks.get(beanName);
if (callback != null) {
callback.accept(singletonObject);
}
}
/**
* Add the given singleton factory for building the specified singleton
* if necessary.
* <p>To be called for early exposure purposes, for example, to be able to
* resolve circular references.
* @param beanName the name of the bean
* @param singletonFactory the factory for the singleton object
*/
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
addSingleton() 是 Bean 完工的登基仪式:进一级缓存,同时把二级、三级里的痕迹全部清掉 ------同一个 Bean 名下,成品与半成品不共存。addSingletonFactory() 的 javadoc 里那句 "To be called for early exposure purposes, for example, to be able to resolve circular references" 直接点题:三级缓存就是为循环引用而生的。
而调用工厂的那条链(getSingleton(beanName, true) 第三级)最终能跑起来,靠的是外层这个方法------它也是 doGetBean() 创建单例的入口,这里节选主干(6.2 在锁的处理上新增了不少 lenient creation 分支,与本文主线无关,以(略)标注):
java
@SuppressWarnings("NullAway")
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
Thread currentThread = Thread.currentThread();
Boolean lockFlag = isCurrentThreadAllowedToHoldSingletonLock();
boolean acquireLock = !Boolean.FALSE.equals(lockFlag);
boolean locked = (acquireLock && this.singletonLock.tryLock());
try {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
// ...(略:6.2 新增------单例锁被占用时的 lenient creation 分支与等待处理)
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
try {
beforeSingletonCreation(beanName);
}
catch (BeanCurrentlyInCreationException ex) {
// ...(略:6.2 新增------lenient creation 场景下的等待与重试)
}
boolean newSingleton = false;
boolean recordSuppressedExceptions = (locked && this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// Leniently created singleton object could have appeared in the meantime.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
this.currentCreationThreads.put(beanName, currentThread);
try {
singletonObject = singletonFactory.getObject();
}
finally {
this.currentCreationThreads.remove(beanName);
}
newSingleton = true;
}
}
// ...(略:IllegalStateException / BeanCreationException 的补偿处理)
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
try {
addSingleton(beanName, singletonObject);
}
catch (IllegalStateException ex) {
// Leniently accept same instance if implicitly appeared.
Object object = this.singletonObjects.get(beanName);
if (singletonObject != object) {
throw ex;
}
}
}
}
return singletonObject;
}
finally {
// ...(略:锁与 lenient creation 状态的清理)
}
}
主干还是经典三段式:beforeSingletonCreation() 登记 → singletonFactory.getObject()(即 createBean() → doCreateBean())→ addSingleton() 登记成品。singletonFactory.getObject() 执行期间,该 Bean 一直在"创建中"名单上------这正是别的 Bean 此时来要它的早期引用能走通二级、三级的前提。
3.3 getEarlyBeanReference:为什么两级缓存不够
工厂里藏的那句 getEarlyBeanReference(beanName, mbd, bean) 还没展开,现在看它。这是 AbstractAutowireCapableBeanFactory 里的方法:
java
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
* @param beanName the name of the bean (for error handling purposes)
* @param mbd the merged bean definition for the bean
* @param bean the raw bean instance
* @return the object to expose as bean reference
*/
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
exposedObject = bp.getEarlyBeanReference(exposedObject, beanName);
}
}
return exposedObject;
}
逻辑很短:把裸对象依次交给所有 SmartInstantiationAwareBeanPostProcessor,让它们有机会把返回的引用换成别的对象 。看接口定义(spring-beans 的 org.springframework.beans.factory.config 包):
java
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
* <p>This callback gives post-processors a chance to expose a wrapper
* early - that is, before the target bean instance is fully initialized.
* The exposed object should be equivalent to what
* {@link #postProcessBeforeInitialization} / {@link #postProcessAfterInitialization}
* would expose otherwise. Note that the object returned by this method will
* be used as the bean reference unless the post-processor returns a different
* wrapper from said post-process callbacks. In other words, those post-process
* callbacks may either eventually expose the same reference or alternatively
* return the raw bean instance from those subsequent callbacks (if the wrapper
* for the affected bean has been built for a call to this method already,
* it will be exposed as the final bean reference by default).
* <p>The default implementation returns the given {@code bean} as-is.
* @param bean the raw bean instance
* @param beanName the name of the bean
* @return the object to expose as the bean reference
* (typically the passed-in bean instance as default)
* @throws org.springframework.beans.BeansException in case of errors
*/
default Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
return bean;
}
javadoc 的关键句翻译过来:这个回调给后置处理器一个机会,在目标 Bean 完全初始化之前就提前暴露一个包装对象(wrapper);它暴露的对象应当与 postProcessAfterInitialization() 最终暴露的等价 。默认实现原样返回 bean------所以没有 AOP 时早期引用就是裸对象;而 AOP 场景下,AbstractAutoProxyCreator 实现了这个方法,在这里就把代理对象创建出来返回 (下一篇 AOP 原理会详细拆它的 postProcessAfterInitialization() 与 getEarlyBeanReference() 的协作)。
现在可以正面回答 1.2 节的问题了------为什么两级缓存不够:
- 代理的生成时机被约束在"初始化之后",这是为了让代理包装的是完整初始化后的目标对象;
- 但循环依赖场景下,B 在 A 初始化完成之前 就需要 A 的引用。如果只缓存对象(两级),Spring 只能二选一:要么在实例化后立刻给所有 Bean 生成代理放进二级缓存(无 AOP 需求的 Bean 白白多付代理成本,还破坏了初始化后代理的设计),要么给 B 一个裸对象(B 注入的 A 与容器最终的 A 不是同一个对象,AOP 增强对 B 失效);
- 引入第三级存工厂 后,"要不要代理、怎么代理"这个决定被推迟到真正有人来要引用的那一刻 ,并且只问一次。没有循环依赖,工厂永远不被执行,零成本;有循环依赖且需要代理,代理在暴露时就生成并转存二级,后续初始化完成时
postProcessAfterInitialization()会发现代理已创建而直接复用(javadoc 里说的 "if the wrapper for the affected bean has been built for a call to this method already, it will be exposed as the final bean reference")。
一句话总结:三级缓存不是三个"对象缓存",而是一个"成品缓存 + 一个早期引用缓存 + 一个生产早期引用的决策机制"。前两级解决"半成品存哪",第三级解决"半成品以什么形态暴露"。
3.4 完整走一遍 A/B 循环的调用链
回顾完三个关键方法,把整条链串起��。以 A 先被创建为例,完整时序如下:

对应到源码,几个关键节点再确认一遍:
getBean("a")→doGetBean("a")→getSingleton("a")未命中 →getSingleton("a", () -> createBean("a", mbd, args))→beforeSingletonCreation("a")把 a 写进"创建中"名单 →doCreateBean("a", ...);- A 实例化完成,
earlySingletonExposure三个条件全满足 →addSingletonFactory("a", 工厂),工厂进三级缓存; populateBean(A)填充属性,发现依赖 B → 触发getBean("b"),递归 进入同样的流程:B 实例化、B 的工厂进三级缓存、populateBean(B)发现依赖 A → 触发getBean("a");getSingleton("a", true)三级递进:一级无 → a 在创建中 → 二级无 → 三级工厂执行 →getEarlyBeanReference()产出 A 的早期引用 → 工厂移除、引用转存二级 → 返回给 B;- B 注入 A 的引用,
initializeBean(B)完成 →addSingleton("b"):B 进一级缓存,二级三级中 B 的痕迹清除; - 递归返回,回到第 3 步 A 的
populateBean(),B 注入成功 →initializeBean(A)完成; doCreateBean()的收尾还有一段最终检查,这是理解"早期引用到底是什么"的最后一块拼图:
java
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = CollectionUtils.newLinkedHashSet(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
注意 getSingleton(beanName, false) 的第二个参数传了 false ------不允许创建早期引用,只查一级和二级。查到的 earlySingletonReference 是二级缓存里那份早期引用(第 4 步转存进去的)。两种情况:
exposedObject == bean:初始化过程中没有后置处理器把对象换掉(无代理生成),最终暴露的对象就用二级缓存里那份------它就是裸对象本身,无缝替换;- 反之,如果初始化后生成了新的 包装对象(与早期引用不是同一个),就进入
allowRawInjectionDespiteWrapping的判断:默认 false 意味着宁可报错也不把不一致的状态留给用户 ------因为已经有别的 Bean(B)注入了 A 的早期引用(可能是代理),而初始化后 A 的最终对象又变了,B 拿到的就不是最终版本。这个异常信息本身就是最好的文档:"has been injected into other beans ... in its raw version as part of a circular reference, but has eventually been wrapped"。
allowRawInjectionDespiteWrapping 的字段注释原文也印证了这个语义:
java
/**
* Whether to resort to injecting a raw bean instance in case of circular reference,
* even if the injected bean eventually got wrapped.
*/
private boolean allowRawInjectionDespiteWrapping = false;
默认 false:不允许"注入了裸对象、最终却是包装对象"的不一致发生。只有显式打开它,才会容忍这种不一致(作为循环依赖实在解不开时的最后手段)。
3.5 边界场景:三种解不开/另一种解法
主流程走通了,再看三个边界,它们共同划定了三级缓存的能力边界。
3.5.1 构造器注入循环:无解
Field/setter 注入的循环依赖能解,靠的是"实例化"和"属性填充"是两步------实例化后有一个可以暴露的中间态。而构造器注入把依赖获取提前到了实例化这一步 :创建 A 就要先有 B 的实例,B 还没实例化,三级缓存里连工厂都还没来得及放(addSingletonFactory() 在实例化之后才执行)。
解环现场实际上是这样死的:A 构造器要 B → getBean("b") → B 开始创建,beforeSingletonCreation("b") 成功 → B 构造器要 A → getBean("a") → a 在创建中、一二级缓存皆无(工厂不存在)→ 走到创建分支的 beforeSingletonCreation("a") → add() 返回 false → 抛出 BeanCurrentlyInCreationException(即 3.2 节贴的那段守门员代码)。链条绕了一圈回到原点,没有裸对象可暴露,死锁无解------唯一的出路是打破环本身(重构)或者用 @Lazy(下一小节)。
3.5.2 prototype 循环:不缓存
earlySingletonExposure 的第一个条件就是 mbd.isSingleton()。prototype 作用域的 Bean 每次获取都新建实例,Spring 不缓存它们,自然也没有"半成品暴露"一说。prototype 的循环依赖防护靠的是另一套"创建中"名单,看 doGetBean() 的两处:
java
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
java
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
思路与单例一致:beforePrototypeCreation() 登记进 prototype 的创建中名单(ThreadLocal 结构),循环依赖时第二次进入同名 Bean 的创建直接抛 BeanCurrentlyInCreationException。区别在于 prototype 没有任何缓存可用,环必须由使用者打破。
3.5.3 @Lazy:ObjectFactory 延迟代理
@Lazy 提供了第三种思路:不是提前暴露半成品,而是先注入一个"以后再去拿"的代理 。它不走三级缓存,而是属性填充阶段的另一个入口。看 spring-context 的 ContextAnnotationAutowireCandidateResolver:
java
@Override
@Nullable
public Object getLazyResolutionProxyIfNecessary(DependencyDescriptor descriptor, @Nullable String beanName) {
return (isLazy(descriptor) ? buildLazyResolutionProxy(descriptor, beanName) : null);
}
注入点上有 @Lazy 且 value() 为 true 时,不立刻解析依赖,而是构建一个代理:
java
private Object buildLazyResolutionProxy(
DependencyDescriptor descriptor, @Nullable String beanName, boolean classOnly) {
if (!(getBeanFactory() instanceof DefaultListableBeanFactory dlbf)) {
throw new IllegalStateException("Lazy resolution only supported with DefaultListableBeanFactory");
}
TargetSource ts = new LazyDependencyTargetSource(dlbf, descriptor, beanName);
ProxyFactory pf = new ProxyFactory();
pf.setTargetSource(ts);
Class<?> dependencyType = descriptor.getDependencyType();
if (dependencyType.isInterface()) {
pf.addInterface(dependencyType);
}
ClassLoader classLoader = dlbf.getBeanClassLoader();
return (classOnly ? pf.getProxyClass(classLoader) : pf.getProxy(classLoader));
}
ProxyFactory 挂的 TargetSource 是 LazyDependencyTargetSource,核心在它的 getTarget():
java
@Override
@SuppressWarnings("NullAway")
public Object getTarget() {
Object cachedTarget = this.cachedTarget;
if (cachedTarget != null) {
return cachedTarget;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(2);
Object target = this.beanFactory.doResolveDependency(
this.descriptor, this.beanName, autowiredBeanNames, null);
// ...(略:target 为 null 或集合类型的兜底处理)
串起来:注入发生时,B 位置上放的是这个延迟代理 (此刻 B 根本没创建,环没有被触发);等真正调用 B 的方法时,代理的 getTarget() 才触发 doResolveDependency() → getBean("b")------此时 A 早已创建完成,B 顺利创建。依赖的解析从"注入时"推迟到"首次使用时" ,环被时间差拆掉了。注意这个代理是 ProxyFactory 现场构建的(JDK 动态代理或 CGLIB),与 AOP 的自动代理是两回事;接口依赖用 JDK 代理,类依赖走 CGLIB。
三个边界场景汇总对比:
| 场景 | 能否自动解 | 机制 | 结果 |
|---|---|---|---|
| field/setter 注入单例循环 | 能 | 三级缓存提前暴露早期引用 | 双方注入彼此的引用,正常初始化 |
| 构造器注入单例循环 | 不能 | 实例化阶段就要依赖,无半成品可暴露 | BeanCurrentlyInCreationException |
| prototype 循环 | 不能 | 无缓存,仅有创建中名单防重入 | BeanCurrentlyInCreationException |
构造器循环 + @Lazy |
能 | 延迟代理,注入与解析分离 | 启动成功,首次调用时解析依赖 |
四、Demo 实战验证
以上所有场景整理成一个可运行的纯 Java Maven 工程(文末有完整代码地址),三种循环场景各一个包,关键代码如下:
场景一,field 注入循环(@Autowired 属性注入,走三级缓存):
java
@Component
public class FieldA {
@Autowired
private FieldB b;
public FieldB getB() {
return b;
}
}
@Component
public class FieldB {
@Autowired
private FieldA a;
public FieldA getA() {
return a;
}
}
场景二,构造器注入循环(无解,验证异常):
java
@Component
public class ConstructorA {
private final ConstructorB b;
public ConstructorA(ConstructorB b) {
this.b = b;
}
}
@Component
public class ConstructorB {
private final ConstructorA a;
public ConstructorB(ConstructorA a) {
this.a = a;
}
}
场景三,构造器循环 + @Lazy(延迟代理解开环):
java
@Component
public class LazyA {
private final LazyB b;
public LazyA(@Lazy LazyB b) {
this.b = b;
System.out.println("[LazyA] 构造完成,此刻 b 是延迟代理:" + b.getClass().getName());
}
}
@Component
public class LazyB {
private final LazyA a;
public LazyB(LazyA a) {
this.a = a;
}
}
三个场景各起一个独立的 AnnotationConfigApplicationContext,逐一验证:
java
public class Main {
public static void main(String[] args) {
scenario1FieldInjection();
scenario2ConstructorInjection();
scenario3LazyBreaksCycle();
}
private static void scenario1FieldInjection() {
System.out.println("===== 场景一:field 注入循环依赖 =====");
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext("com.example.cycle.field")) {
FieldA a = ctx.getBean(FieldA.class);
FieldB b = ctx.getBean(FieldB.class);
System.out.println("启动成功,a = " + a + ", b = " + b);
System.out.println("a.b == b ? " + (a.getB() == b));
System.out.println("b.a == a ? " + (b.getA() == a));
}
}
private static void scenario2ConstructorInjection() {
System.out.println("===== 场景二:构造器注入循环依赖 =====");
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext("com.example.cycle.constructor")) {
System.out.println("启动成功(不应走到这里)");
}
catch (Exception e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
System.out.println("启动失败,根因:" + root.getClass().getSimpleName());
System.out.println("消息:" + root.getMessage());
}
}
private static void scenario3LazyBreaksCycle() {
System.out.println("===== 场景三:构造器循环 + @Lazy =====");
try (AnnotationConfigApplicationContext ctx =
new AnnotationConfigApplicationContext("com.example.cycle.lazy")) {
LazyA a = ctx.getBean(LazyA.class);
System.out.println("启动成功,a = " + a);
System.out.println("首次调用 b.sayHi()(此刻才真正解析 LazyB)");
a.callB();
}
}
}
运行结果与源码分析完全对应(本地实测输出):
| 场景 | 容器启动 | 关键现象 | 对应源码机制 |
|---|---|---|---|
| 一:field 注入循环 | 成功 | a.b == b 为 true,b.a == a 为 true,四者同一对象引用互通 |
三级缓存工厂产出早期引用转存二级,双方注入同一引用 |
| 二:构造器注入循环 | 失败 | 根因 BeanCurrentlyInCreationException:"Requested bean is currently in creation" |
beforeSingletonCreation() 守门员,无半成品可暴露 |
三:构造器循环 + @Lazy |
成功 | 构造时 b 是 $Proxy/CGLIB 增强类,callB() 首次调用才触发 LazyB 创建 |
getLazyResolutionProxyIfNecessary() 延迟代理 |
场景一能验证"双方注入的是同一份引用"这一点尤其值得玩味:A 的属性里那个 B,和 B 自己,是 == 相等的;A、B 之间通过二级缓存的同一份早期引用互指,环在对象图层面真实闭合。
最后用一张图把本文的知识点归纳一下:

五、总结
三级缓存的本质是"半成品暴露"机制:一级 singletonObjects 存成品,二级 earlySingletonObjects 存提前暴露的早期引用,三级 singletonFactories 存"如何生产早期引用"的工厂------第三级的存在让 AOP 代理可以在暴露那一刻按需生成,既不提前给所有 Bean 付代理成本,又保证注入给对方的引用与最终对象一致。能力边界也很清晰:构造器注入与 prototype 无中间态可暴露,环只能靠 @Lazy 或重构打破。
下一篇我们进入 AOP 原理(上):代理的创建------AbstractAutoProxyCreator 如何在初始化之后(以及循环依赖暴露时)为 Bean 织入增强,JDK 动态代理与 CGLIB 的选择逻辑。
Demo 完整代码 :Spring/S06-循环依赖/circular-dependency-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+源码分析(十一)视图渲染与异步
- Spring 源码分析(一)IOC 容器总览与 refresh() 全景
- Spring 源码分析(二)配置类的解析与扫描
- Spring 源码分析(三)BeanFactoryPostProcessor 与占位符
- Spring 源码分析(四)Bean 生命周期(上):实例化与属性填充
- Spring 源码分析(五)Bean 生命周期(下)
本文为「源码学习」专栏系列文章,转载请注明出处。相互学习,共同进步!