源码小说CodeStory
登录
上一章

44,463 字 · 约 111 分钟

下一章
字体

主题

版式

第11章 卷三 · 成器 · 过手的人:BeanPostProcessor

过⼿的⼈:BeanPostProcessor「我签的合同只有两条,每条都写着 default ,每条都返回 Object 。 就是这个 Object ——不是 void ——让我有资格把⼿⾥的东⻄换成另⼀个。」 ——BeanPostProcessor , @since 10.10.2003开场:那件器不是你造的那件先做⼀个很⼩的实验。

你在 OrderServiceImpl 上打了 @Transactional ,在另⼀处 @Autowired 把它注进来,然后打印⼀⾏:

System.out.println(orderService.getClass().getName());

你期待 com.foo.OrderServiceImpl 。你看到的是 com.foo.OrderServiceImpl$$SpringCGLIB$$0 。

这⼀刻⼤多数⼈会问"Spring 是怎么把代理织进去的",然后⼀头扎进 AOP 的⽂档⾥找"织⼊"这个词。这条路是错的。AOP 没有任何魔法织⼊。 它只是站在⼀条早就修好的流⽔线的某⼀道⼝⼦上,趁着容器把新造好的器递过来的那⼀瞬间,把它换成了别的东⻄,然后⼀脸平静地交了回去。

这条流⽔线上的⼝⼦,就是 BeanPostProcessor 。这⼀章要讲的,是成器坊⾥那⼀排「过⼿的⼈」——每⼀件器从料变成成品的过程中,都要经过他们的⼿;他们不但能看、能改,还能掉包。

先记住⼀句话,本章所有细节都是它的展开:

BeanPostProcessor 的两个⽅法返回的不是 void ,是 Object 。整个 Spring ⽣态⾥"递到你⼿上的不是原件"这件事,全部来源于这⼀个类型选择。

⼀、契约窄到只剩两句话先看合同本身。

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/config/BeanPostProcessor.java:67

public interface BeanPostProcessor {
default @Nullable Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
default @Nullable Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}

(两个⽅法分别在 :82 和 :107 。)

做了什么:在⼀件器"初始化"( afterPropertiesSet / init-method )的前后各开⼀道⼝⼦。javadoc 对返回值只有⼀句话的解释,但这句话是整章的题眼:

"the bean instance to use, either the original or a wrapped one"

为什么这么设计:如果签名是 void postProcess(Object bean, String beanName) ,你只能改这件器的内部状态——设个字段、调个 setter、注册到某张表⾥。有了Object 返回值,你就能返回⼀个完全不同的对象。 @Transactional 、 @Cacheable 、 @Async 、 @Retryable 、Spring Security 的⽅法级鉴权,以及测试⾥的@MockitoSpyBean ,全部⾛这同⼀个⼝⼦。⼀次类型选择,撑起了半个⽣态。

精妙在哪:这个接⼝是 Spring 最古⽼的⼀批 SPI 之⼀。看它的 @since 标签( [framework] .../config/BeanPostProcessor.java:61 )——写的是 10.10.2003 ,⼀个⽇期,不是版本号。它⽐ Spring ⾃⼰的 @since 版本号规范还⽼。⼆⼗多年过去,签名⼀个字没改,只是从抽象⽅法变成了 default ⽅法。

坑在哪:坑就在返回值的另⼀半语义上。看容器怎么遍历这条链:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:424

Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {

return result; // ←不是返回 null,是"到此为⽌"

}
result = current;
}
return result;

返回 null 不会把 bean 变成 null ,⽽是让整条链在这⾥静默截断,⽤上⼀个⼈的成果收⼯。

这是本章第⼀处必须批评的地⽅。同⼀个返回通道,被⽤来表达两件毫不相⼲的事:⼀是"这是我加⼯后的成品",⼆是"别往下传了"。这两件事没有任何语义关联,却共⽤⼀个null 。后果是:你⾃⼰写的某个 BPP ⾥⼿滑写了 return maybeNull() ,容器不会报错、不会警告、不会打⽇志——它只会安静地跳过后⾯所有 BPP。⽽ auto-proxycreator 通常排在后⾯(下⽂ §六会算清它的位置)。于是你的 @Transactional 就这么消失了,堆栈⼲净,⽇志空⽩,你排查三天。

javadoc 确实写了这条( @return ... if {@code null}, no subsequent BeanPostProcessors will be invoked )。但"⽂档⾥写了"和"接⼝设计得让⼈不容易写错"是两

回事。⼀个 Optional<Object> 、或者⼀个显式的 PostProcessResult.stop() ,都能把这两种语义拆开。⼆⼗年没改,⼤概率是因为改不动——这个接⼝的实现者遍布整个Java ⽣态。

⼆、五个⼈,站在不同的位置BeanPostProcessor 只开了两道⼝⼦。但容器造⼀件器远不⽌"初始化前后"两个瞬间。于是往下派⽣了四个更专⻔的接⼝:

BeanPostProcessor [config 包]

├── InstantiationAwareBeanPostProcessor [config 包]
│ └── SmartInstantiationAwareBeanPostProcessor [config 包]
├── DestructionAwareBeanPostProcessor [config 包]
└── MergedBeanDefinitionPostProcessor [support 包 ← 注意]

接⼝ 坐标(均在 [framework] spring-beans/src/main/java/ ) @sinceBeanPostProcessor .../beans/factory/config/BeanPostProcessor.java:67 10.10.2003InstantiationAwareBeanPostProcessor .../beans/factory/config/InstantiationAwareBeanPostProcessor.java:44 1.2SmartInstantiationAwareBeanPostProcessor .../beans/factory/config/SmartInstantiationAwareBeanPostProcessor.java:37 2.0.3DestructionAwareBeanPostProcessor .../beans/factory/config/DestructionAwareBeanPostProcessor.java:30 1.0.1MergedBeanDefinitionPostProcessor .../beans/factory/support/MergedBeanDefinitionPostProcessor.java:38 2.5第⼀个要点破的细节: MergedBeanDefinitionPostProcessor 不在 config 包,在 support 包。五兄弟⾥唯⼀的例外。写⽂章时顺⼿写成 config 是最常⻅的低级错误之⼀——我第⼀遍也差点写错,是回源才发现的( grep -n package 那⼀⾏明明⽩⽩: package org.springframework.beans.factory.support; )。

为什么它特殊?因为其余四个都是"对实例动⼿"的⼝⼦,只有它是"对图纸动⼿"的⼝⼦——它拿到的第⼀个参数是 RootBeanDefinition ,是那张合并后的图纸,不是器。它在support 包,和 RootBeanDefinition 做邻居,位置其实是对的。

第⼆个要点破的:两个 InstantiationAware 接⼝的 javadoc 都在主动劝退你:

"NOTE: This interface is a special purpose interface, mainly for internal use within the framework. It is recommended to implement the plain BeanPostProcessorinterface as far as possible." [framework] .../config/InstantiationAwareBeanPostProcessor.java:34-36 ( Smart 那版在 :29-32 ,措辞略有不同)

这不是客套。往下每多继承⼀层,你能插⼿的时机就越早,⽽越早的时机上,容器对这件器的了解就越少、你能搞砸的东⻄就越多。框架把这⼏层留给⾃⼰⽤。

本基线如此:Framework 5.x 时代⼈尽皆知的便利基类 InstantiationAwareBeanPostProcessorAdapter ,在本仓已经彻底不存在( find /tmp/sf-src -name"InstantiationAwareBeanPostProcessorAdapter.java" ⽆任何输出)。它的历史使命是"让你只重写想要的那个⽅法",⽽现在接⼝⽅法本身全是 default ,Adapter ⾃然没了存在意义。同样消失的还有 postProcessPropertyValues(...) ——全仓只在⼀⾏注释⾥还留着这个词:

// [framework] spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java:275

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
return pvs; // skip postProcessPropertyValues
}

⽹上⼤量讲 BPP 的中⽂⽂章还在教你"继承 Adapter"。在 Framework 7 上,那段代码编译不过。

三、⼀条流⽔线上,⼗⼀个瞬间

现在把镜头拉到 AbstractAutowireCapableBeanFactory ——造器的主舞台。⼊⼝是 createBean(...) ( [framework]

.../support/AbstractAutowireCapableBeanFactory.java:488 )。我按容器实际执⾏的先后,把⼝⼦⼀道道数下来。

时机 A · 还没下料,就有⼈拦路

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java:512

try {

// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.

Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {

return bean; // ←整条流⽔线到此为⽌

}
}

resolveBeforeInstantiation 本体在 :1124 :

if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}

做了什么:在构造器还没被调⽤之前,问⼀圈 InstantiationAware 那批⼈:"这件器要不要我⾃⼰造?"谁第⼀个返回⾮ null ,谁就接管了——遍历循环在任何⼀个⾮null 处⽴刻 return ( :1153-1161 )。

为什么这么设计:为了让"⽬标对象根本不需要被 new 出来"成为可能。池化⽬标、懒初始化⽬标、远程代理,都靠这条路。接⼝ javadoc ⾥那句 "suppress defaultinstantiation for specific target beans"( .../config/InstantiationAwareBeanPostProcessor.java:29 ),说的就是这⾥, @see 甚⾄直接点名了LazyInitTargetSourceCreator 。

⚠ 暗礁 1(本章最狠的⼀条):从这条路短路出来的 bean,只经过 postProcessAfterInitialization 这⼀道( :1133 )。它不⾛ populateBean 、不⾛

initializeBean 、不⾛ invokeAwareMethods 、不⾛ @PostConstruct / afterPropertiesSet / init-method 、也不⾛registerDisposableBeanIfNecessary ——因为 createBean 在 :516 就 return 了,压根没进 doCreateBean 。也就是说: @Autowired 不注⼊,@PreDestroy 不调⽤。 这条特例罕⻅到 BeanPostProcessor ⾃⼰的 javadoc 都要专⻔加⼀段:

"This callback will also be invoked after a short-circuiting triggered by a InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiationmethod, in contrast to all other BeanPostProcessor callbacks." [framework] .../config/BeanPostProcessor.java:95-97

⚠ 暗礁 2: mbd.beforeInstantiationResolved 是个三态字段( null / TRUE / FALSE ,声明在 [framework]

.../support/RootBeanDefinition.java:116 )。它会记住"上次问过,没⼈接管",之后同⼀张图纸再造器就直接跳过整个时机 A( :1126 、 :1137 )。运⾏时后加进来的 InstantiationAware BPP,对已经被判过 FALSE 的图纸完全⽆效。

时机 B · ⽤哪个构造器,问他们createBeanInstance 在挑构造器时会先问 Smart ⼀族( :1216 → determineConstructorsFromBeanPostProcessors , :1314 )。同样是"第⼀个返回⾮ null 就⽤它"。这⼀道⼝⼦的最⼤消费者是 AutowiredAnnotationBeanPostProcessor ——§五会拆开它。

时机 C · 图纸合并完,给你⼀次改元数据的机会// [framework] .../support/AbstractAutowireCapableBeanFactory.java:574

synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) { ... }
mbd.markAsPostProcessed();
}
}

做了什么:器已经实例化、属性还没填的当⼝,把合并后的图纸交给所有 MergedBeanDefinitionPostProcessor 过⼀遍。

精妙在哪:注意那个 mbd.postProcessed ⻔闩(字段初值 false , [framework] .../support/RootBeanDefinition.java:113 ;置位⽅法 markAsPostProcessed()

在同⽂件 :449 )。每张图纸只跑⼀次。 这就是 @Autowired / @Resource 的注⼊点元数据"反射扫全类"这件昂贵的事只发⽣⼀次的根本原因——不是靠某个缓存 Map 的运⽓,是靠图纸上的⼀个布尔位。

时机 D · 把半成品先递出去// [framework] .../support/AbstractAutowireCapableBeanFactory.java:589

boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {

...

addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

getEarlyBeanReference 只问 smartInstantiationAware 这⼀张表( :966-974 )。这道⼝⼦是循环依赖的全部戏眼,ch11 会整章讲它,这⾥只钉两个默认值:

默认值核实(两仓相反,这是最容易被⽹⽂写错的⼀处) - [framework] .../support/AbstractAutowireCapableBeanFactory.java:131 : private boolean

allowCircularReferences = true; —— Framework 侧默认允许。 - [boot] core/spring-
boot/src/main/java/org/springframework/boot/ApplicationProperties.java:49 : private boolean allowCircularReferences; —— 没有显式初始化,Java

布尔字段默认 false ,Boot 侧默认禁⽌。落点在 [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:388 :

autowireCapableBeanFactory.setAllowCircularReferences(this.properties.isAllowCircularReferences());

所以"Spring 默认允许循环依赖"和"Spring 默认禁⽌循环依赖"这两句话都对,也都不完整——取决于你说的是哪个仓。 spring.main.allow-circular-references 这个属性,就是 Boot 给你把 Framework 的默认值扳回来的开关。

时机 E / F · 属性填充前的两道// [framework] .../support/AbstractAutowireCapableBeanFactory.java:1416(populateBean起点 :1390)

if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return; // ←直接从 populateBean返回
}
}
}

⚠ 暗礁 3 —— 契约⽂档与实现不匹配。接⼝ javadoc 只说了返回 false 的⼀半后果:"Returning false will also prevent any subsequent

InstantiationAwareBeanPostProcessor instances being invoked on this bean instance."( [framework].../config/InstantiationAwareBeanPostProcessor.java:84-85 )。⽽真实后果是整个 populateBean 直接 return —— @Autowired 、 @Value 、 @Resource 、

XML 的 <property> 、 autowireByName / autowireByType ,全部作废。javadoc 的 @return ⼀栏写了 " false if property population should be skipped",勉强

算提了,但那句显眼的 Returning false will also... 把读者的注意⼒全引到"后续 BPP"上去了。这是⽂档措辞把重点排错了序。

紧接着是时机 F:

// [framework] .../support/AbstractAutowireCapableBeanFactory.java:1439

if (hasInstantiationAwareBeanPostProcessors()) {
if (pvs == null) { pvs = mbd.getPropertyValues(); }
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) { return; }
pvs = pvsToUse;
}
}

这就是 @Autowired 和 @Resource 真正⼲活的地⽅。 不是在什么神秘的"注⼊阶段",就是在这个 for 循环⾥。

🦴 ⻣灰级细节: isSynthetic 守卫的不对称。 把时机 E 和时机 F 的守卫并排看: - E( :1416 ): !mbd.isSynthetic() &&

hasInstantiationAwareBeanPostProcessors() - F( :1439 ):只有 hasInstantiationAwareBeanPostProcessors()

时机 F 没有 isSynthetic 检查。 我把全⽂件⾥所有 isSynthetic 守卫都数了⼀遍:时机 A( :1128 )、时机 D( :968 )、时机 E( :1416 )、时机 I( :656 )、initializeBean 前后两道( :1806 、 :1817 )——全有守卫;唯独 postProcessProperties 没有。

净效果:⼀个 synthetic 的 bean 定义(框架内部合成的那种),会跳过实例化前、跳过早期引⽤、跳过实例化后、跳过初始化前后全部四类回调,但仍然会⽼⽼实实经过postProcessProperties 。这个不对称在源码⾥没有任何注释解释。它可能是有意的(synthetic bean 也需要依赖注⼊),也可能是历史遗留—— postProcessProperties 是@since 5.1 才加的⽅法( .../config/InstantiationAwareBeanPostProcessor.java:103 ),是这⼀组⾥最年轻的⼀个。此处我未能从仓库内找到确凿依据判定是哪⼀种,如实标出。

🦴 顺带⼀条本基线的 record 处理(在时机 E 之前, :1402 ):

if (bw.getWrappedClass().isRecord()) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(..., "Cannot apply property values to a record");
}
else {

// Skip property population phase for records since they are immutable.

return;
}
}

record 类型的 bean 直接跳过整个属性填充阶段。 你在 record 上写 @Autowired 字段,不会报错,也不会⽣效。

时机 G · 初始化前后(最⼴为⼈知的那两道)

// [framework] .../support/AbstractAutowireCapableBeanFactory.java:1797

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
if (bean.getClass() == NullBean.class) { return bean; }
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try { invokeInitMethods(beanName, wrappedBean, mbd); }
catch (Throwable ex) { ... }
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}

注意变量名: bean 进去, wrappedBean 出来。这个名字本身就是这⼀章的注脚。

🦴 invokeAwareMethods ( :1824 )只处理三个 Aware: BeanNameAware 、 BeanClassLoaderAware 、 BeanFactoryAware ,⽽且外层先判 bean instanceof Aware 才

进。你天天⽤的 ApplicationContextAware 、 EnvironmentAware 、 ResourceLoaderAware 不在这⾥——它们是被⼀个叫 ApplicationContextAwareProcessor 的 BPP

在 postProcessBeforeInitialization ⾥回调的( [framework] spring-context/src/main/java/org/springframework/context/support/ApplicationContextAwareProcessor.java:66 ,类是包级私有的;⼊⼝在 :83 ,实际回调在 :90 的invokeAwareInterfaces ,共七个 Aware)。

这是⼀条很能说明问题的分界线: spring-beans 模块只知道那三个最基础的 Aware,因为它只有作坊、没有总装房; ApplicationContext 独有的那四五个 Aware,只能靠⼀个 BPP 从外⾯补进去。BPP 在这⾥的作⽤不是"扩展点",是"模块解耦的粘合剂"。

本基线如此: applyBeanPostProcessorsBeforeInitialization / AfterInitialization 这两个公开⽅法已被废弃—— @Deprecated(since = "6.1") ,接⼝侧在

[framework] .../config/AutowireCapableBeanFactory.java:301-306 与 :321-326 ,实现侧在 [framework]

.../support/AbstractAutowireCapableBeanFactory.java:419 与 :435 。javadoc 给的替代品是 initializeBean(Object, String) 。所以你在源码⾥会看到
initializeBean 、 resolveBeforeInstantiation 、 postProcessObjectFromFactoryBean 三处调⽤点都挂着 @SuppressWarnings("deprecation")

( :1796 、 :1123 、 :1932 )——框架在给⾃⼰的⽼⽅法打压制注解,这个画⾯挺有意思。

时机 H · FactoryBean 产出的东⻄也要过⼀遍// [framework] .../support/AbstractAutowireCapableBeanFactory.java:1935

protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
return applyBeanPostProcessorsAfterInitialization(object, beanName);
}

对应 javadoc:"In case of a FactoryBean, this callback will be invoked for both the FactoryBean instance and the objects created by theFactoryBean."( .../config/BeanPostProcessor.java:91-94 )。

所以 FactoryBean.getObject() 吐出来的东⻄也会被 AOP 代理。你的 BPP 若只想管其中⼀种,得⾃⼰写 bean instanceof FactoryBean 分辨——javadoc 明说了这是你的活( :93-94 )。

时机 I / J · 还没造出来,就得说它将来⻓什么样// [framework] .../support/AbstractAutowireCapableBeanFactory.java:652

protected @Nullable Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);
if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
boolean matchingOnlyFactoryBean = (typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class);
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
Class<?> predicted = bp.predictBeanType(targetType, beanName);

...

}
}
return targetType;
}

这是" getBeanNamesForType 凭什么能在器还没造出来时就知道它将来是个代理"的答案。

它还有个孪⽣兄弟 determineBeanType ( @since 6.0 ),全仓唯⼀调⽤点在 AOT / GraalVM 的类型预判路径上: [framework] spring-

context/src/main/java/org/springframework/context/support/GenericApplicationContext.java:475 (外层⽅法 preDetermineBeanTypes(RuntimeHints) 在

:430 ,javadoc 写着 "Pre-determine bean types in order to trigger early proxy class creation")。

两者的分⼯,接⼝ javadoc 讲得极准: predictBeanType "should try to predict the bean type as far as known/cached already, without extra processing steps",determineBeanType "should fully evaluate their processing steps in order to create/initialize a potential proxy class upfront"。⼀个是"你猜猜",⼀个是"你现在就把代理类给我⽣出来"。

时机 K · 临终⼀道// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java:1935

protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {

...

}
}

⚠ 暗礁: prototype 的销毁回调,容器根本不管。 ⾸⾏ !mbd.isPrototype() 就把它排除了。 DestructionAwareBeanPostProcessor 的 javadoc 说得同样明

⽩:"this callback will only apply to beans which the container fully manages the lifecycle for. This is usually the case for singletons and scopedbeans."( .../config/DestructionAwareBeanPostProcessor.java:35-37 )。你在 prototype bean 上写的 @PreDestroy ,永远不会被调⽤。 容器把它造出来交给你,就撒⼿了。

四、掉包:AOP 就是从这个⼝⼦进来的上⾯⼗⼀道⼝⼦讲完,现在看那个把它们全部⽤上的典型选⼿。

// [framework] spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java:96public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport

implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {

它就是⼀个 BeanPostProcessor。 没有字节码织⼊器,没有 agent,没有编译期插件。事务、缓存、异步、限流、鉴权——所有你以为很魔法的东⻄,都从这⼀个类的postProcessAfterInitialization ⾥出来:

// [framework] .../autoproxy/AbstractAutoProxyCreator.java:284@Override

public @Nullable Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (this.earlyBeanReferences.remove(cacheKey) != bean) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}

wrapIfNecessary ( :321 )⾥,掉包动作本身只有五⾏:

Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());

return proxy; // ←交回去的已经不是原来那个对象了

}

读到这⾥,你应该有⼀次顿悟。 这⼀⾏ return proxy; 就是全书那句总纲的后半句——"递到你⼿上的,常常不是原件,是外⾯套了⼀层壳的原件"——的物理实现。原件被塞进 SingletonTargetSource 收起来了,容器登记的、注⼊给别⼈的、你 getBean 拿到的,全是那个 proxy 。

这也是全书最⼤的坑源的物理实现。 壳只能拦住"从外⾯打进来的调⽤"。原件在壳⾥⾯调⾃⼰的⽅法,⾛的是它⾃⼰的⽅法表,根本不经过壳。于是 @Transactional 的⾃调⽤静默失效——同⼀个机制,正反两⾯。这个坑我们在 ch22 展开算账,这⾥先把它的出⽣地钉住:它出⽣在 [framework]

.../autoproxy/AbstractAutoProxyCreator.java:341 这⼀⾏ return proxy; 上。

✨ 官⽅留了后⻔。 wrapIfNecessary 的三道否决闸⻔⾥,第三道是 isInfrastructureClass || shouldSkip ,⽽ shouldSkip 的基类实现只做⼀件事:

// [framework] .../autoproxy/AbstractAutoProxyCreator.java:382

protected boolean shouldSkip(Class<?> beanClass, String beanName) {
return AutoProxyUtils.isOriginalInstance(beanName, beanClass);
}
对应常量在 [framework] .../config/AutowireCapableBeanFactory.java:116 : String ORIGINAL_INSTANCE_SUFFIX = ".ORIGINAL"; ( @since 5.1 ),javadoc 写
着 "in order to enforce the given instance to be returned, i.e. no proxies etc"。也就是说,调 initializeBean(bean, "com.foo.Bar.ORIGINAL") ,你能要到⼀个保证不

被套壳的原件。这是⼀条藏得很深、但确实存在的官⽅逃⽣通道。

🦴 本基线的⼀处新变化:缓存键换了。

/**

  • Build a cache key for the given bean class and bean name.
* <p>Note: As of 7.0.2, this implementation returns a composed cache key
* for bean class plus bean name; or if no bean name specified, then the
* given bean {@code Class} as-is.

*/

// [framework] .../autoproxy/AbstractAutoProxyCreator.java:302

protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
if (StringUtils.hasLength(beanName)) { return new ComposedCacheKey(beanClass, beanName); }
else { return beanClass; }
}
private record ComposedCacheKey(Class<?> beanClass, String beanName) {} 在同⽂件 :619 。javadoc ⾃⼰写的 "As of 7.0.2"。Framework 6 时代的 cacheKey

是 bean 名字(是 FactoryBean 就加 & 前缀)。所有讲"auto-proxy ⽤ FACTORY_BEAN_PREFIX + beanName 做缓存键"的旧⽂章,在这条基线上已经过时。(依据是 javadoc⾥的这句 As of 7.0.2 加当前源码,本仓是浅克隆⽆ git 历史,我没查过 commit。)

掉包不⽌⼀条路。 AbstractAdvisingBeanPostProcessor ⾛的是另⼀套逻辑——它⼿⾥只有⼀个 advisor,谁合适就给谁套。⽽它有⼀个⾮常聪明的分⽀:发现对象已经是代理了,就不再套第⼆层,⽽是把⾃⼰的 advisor 插进已有的链:

// [framework] spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java:94

if (bean instanceof Advised advised) {
if (!advised.isFrozen() && isEligible(AopUtils.getTargetClass(bean))) {
if (this.beforeExistingAdvisors) { advised.addAdvisor(0, this.advisor); }
else if (advised.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE &&
advised.getAdvisorCount() > 0) {
advised.addAdvisor(advised.getAdvisorCount() - 1, this.advisor);
return bean;
}
else { advised.addAdvisor(this.advisor); }
return bean;
}
}

(字段 beforeExistingAdvisors 默认 false ,同⽂件 :43 。) @Async ⾛的就是这条线—— AsyncAnnotationBeanPostProcessor extendsAbstractBeanFactoryAwareAdvisingPostProcessor ( [framework] spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationBeanPostProcessor.java:65 ),不是 auto-proxy creator 那条线。这解释了为什么 @Async 和 @Transactional 的代理⾏为在细节上并不完全⼀样。

五、 @Autowired 落地:⼀个⼈⼲四份活// [framework] spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java:158public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationAwareBeanPostProcessor,

MergedBeanDefinitionPostProcessor, BeanRegistrationAotProcessor, PriorityOrdered, BeanFactoryAware {

⼀⼝⽓实现五个接⼝。 它同时是构造器推断者(时机 B)、元数据加⼯者(时机 C)、属性注⼊者(时机 F)、AOT 贡献者。

构造器⾥注册三种注解:

// [framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:192

this.autowiredAnnotationTypes.add(Autowired.class);
this.autowiredAnnotationTypes.add(Value.class);
try {
this.autowiredAnnotationTypes.add((Class<? extends Annotation>)
ClassUtils.forName("jakarta.inject.Inject", classLoader));
logger.trace("'jakarta.inject.Inject' annotation found and supported for autowiring");
}
catch (ClassNotFoundException ex) {

// jakarta.inject API not available - simply skip.

}

本基线如此:是 jakarta.inject.Inject ,没有 javax.inject 回退分⽀。Framework 7 已全⾯ jakarta 化。

顺带回答⼀个常⻅疑问: @Value ⾛的是哪条路?答案是和 @Autowired 同⼀条——它就在上⾯那个 autowiredAnnotationTypes 集合⾥( :194 ),共⽤整套InjectionMetadata ⻣架。分岔发⽣在依赖解析内部:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java:1675// Step 2: pre-defined value or expression, for example, from @Value

Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
if (value instanceof String strValue) {
String resolvedValue = resolveEmbeddedValue(strValue); // ← ${...}占位符
BeanDefinition bd = ...;
value = evaluateBeanDefinitionString(resolvedValue, bd); // ← #{...} SpEL
}
TypeConverter converter = ...;
return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
}

顺序是写死的:先 ${} 占位符,再 #{} SpEL,最后类型转换。 这个顺序解释了为什么 #{'${my.list}'.split(',')} 能⼯作⽽反过来不⾏。

5.1 "单构造器可以不写 @Autowired "是哪⼀⾏?

determineCandidateConstructors ( :349-452 )近⼀百⾏,规则密密麻麻。但那条⼈⼈都在⽤、⼏乎没⼈说得清出处的规则,只是收尾分⽀⾥的⼀⾏:

// [framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:434

else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}

没有任何构造器带注解,但类⾥恰好只有⼀个构造器,且它带参数 → 就⽤它。 这就是你能写单构造器不加注解的全部依据。

同⼀段⾥还有⼀处很有⼈情味的处理:如果你只标了⼀个 @Autowired(required = false) 的构造器,⼜没有默认构造器可退,容器会打⼀条 INFO:

"single autowire-marked constructor flagged as optional - this constructor is effectively required since there is no default constructor to fall back to"

[framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:425-430它没有报错,只是提醒你:"你以为你写的是可选,其实是必选。"

最后⼀⾏也值得看: return (candidateConstructors.length > 0 ? candidateConstructors : null); ( :451 )——空数组必须转成 null ,因为上层⽤ null 表

示"我没意⻅",⽤空数组表示"我明确认为⼀个候选都没有"。两种语义,靠⼀个三元表达式区分。

5.2 注⼊本身,以及两处⼯程妥协// [framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:490

public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try { metadata.inject(bean, beanName, pvs); }
catch (BeanCreationException ex) { throw ex; }
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
注意它返回的还是传进来那个 pvs 。 @Autowired 根本不⾛ PropertyValues 通道——它直接 ReflectionUtils.makeAccessible(field); field.set(bean,

value); 。它借⽤的只是这道⼝⼦的时机,不是这道⼝⼦的数据通道。

✨ 精妙处⼀: ShortcutDependencyDescriptor 。

第⼀次解析成功、且只匹配到唯⼀⼀个 bean 名、且类型对得上时,容器把"解析请求"换成⼀个记住了答案的变体存起来:

// [framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:774

if (value != null && autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
cachedFieldValue = new ShortcutDependencyDescriptor(desc, autowiredBeanName);
}
}

// [framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:910

private static class ShortcutDependencyDescriptor extends DependencyDescriptor {

@Override

public Object resolveShortcut(BeanFactory beanFactory) {
return beanFactory.getBean(this.shortcut, getDependencyType());
}
}

消费点在依赖解析的第⼀⾏( [framework] .../support/DefaultListableBeanFactory.java:1668 )。净效果:prototype bean 反复创建时,那套昂贵的"按类型找候选 +排歧义 + 打分"只做⼀次,之后退化成⼀次 getBean(name, type) 。 把结果编码进请求本身——这是个很漂亮的设计。

✨ 精妙处⼆:为了注⼊顺序确定,去读 class ⽂件。

// [framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:640// Try reading the class file via ASM for deterministic declaration order...// Unfortunately, the JVM's standard reflection returns methods in arbitrary// order, even between different runs of the same application on the same JVM."同⼀个 JVM 上跑两次,反射返回的⽅法顺序都可能不同。" 这是 JDK 的既定⾏为,不是 bug。为了让 @Autowired ⽅法的执⾏顺序稳定,Spring ⼲脆⽤MetadataReaderFactory (ASM)把 class ⽂件读⼀遍,拿字节码⾥的声明顺序去重排反射结果。⽽且它很克制——只有当"反射找到的⽅法全部在 ASM 集合⾥对上号"才采⽤( :660-663 ), IOException 时只 logger.debug ⼀句就放过( :666-669 )。

这是⼀段愿意为确定性付出额外 I/O 的代码。 它也是⼀个信号:如果你的应⽤启动性能有点⽞学,别忘了框架在这些⻆落⾥默默读过 class ⽂件。

🦴 注⼊顺序的完整规则,在 buildAutowiringMetadata 的最后两⾏( :600-601 ):

elements.addAll(0, sortMethodElements(methodElements, targetClass));
elements.addAll(0, fieldElements);

每⼀层类都往列表头部插,且字段插在⽅法之前。逐层向上直到 Object 停( :602-604 )。净效果:⽗类先于⼦类,同⼀层内字段先于⽅法——正好对上类 javadoc ⾥那句"Fields are injected right after construction of a bean, before any config methods are invoked"。

⚠ 静态成员上的 @Autowired ,只打⼀条 INFO 就跳过(字段在 :562 、⽅法在 :580 ,都是 logger.info("Autowired annotation is not supported on static

...") 然后 return )。默认⽇志级别下你看不到它。记住这⼀条,下⼀节⻢上要拿它做对⽐。

六、 @Resource ⼀家:同⼀件事,两种脾⽓// [framework] spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java:141public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBeanPostProcessor

implements InstantiationAwareBeanPostProcessor, BeanFactoryAware, Serializable {

位置提醒:它在 spring-context 的 context.annotation 包;它的⽗类 InitDestroyAnnotationBeanPostProcessor 在 spring-beans 的beans.factory.annotation 包( [framework] spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java:87 )。跨模块继承,别搞混。

注意它不是 Smart——不参与构造器推断,不参与早期引⽤。它只管 @Resource 的注⼊和 @PostConstruct / @PreDestroy 的调⽤。

6.1 缺⼀个 jar, @PostConstruct 就静默失效

// [framework] .../annotation/CommonAnnotationBeanPostProcessor.java:190

public CommonAnnotationBeanPostProcessor() {
setOrder(Ordered.LOWEST_PRECEDENCE - 3);

// Jakarta EE 9 set of annotations in jakarta.annotation package

addInitAnnotationType(AnnotationUtils.loadAnnotationType("jakarta.annotation.PostConstruct"));
addDestroyAnnotationType(AnnotationUtils.loadAnnotationType("jakarta.annotation.PreDestroy"));

...

}

本基线如此:只有 jakarta.* ,没有任何 javax.* 回退(全类唯⼀的 javax 是 javax.naming.InitialContext ,那是 JDK ⾃带的 JNDI 类, :145-146 )。

更狠的是注册条件:

// [framework] spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigUtils.java:119

private static final boolean JAKARTA_ANNOTATIONS_PRESENT =
ClassUtils.isPresent("jakarta.annotation.PostConstruct", classLoader);

// [framework] .../annotation/AnnotationConfigUtils.java:170

if (JAKARTA_ANNOTATIONS_PRESENT && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);

...

}

classpath 上没有 jakarta.annotation.PostConstruct ,这个处理器根本不会被注册。 你的 @PostConstruct 不报错、不警告,就是不执⾏。这是 Java EE → Jakarta 迁移期最经典的⼀个坑:你把注解从 javax.annotation 改成了 jakarta.annotation ,但依赖忘了加,编译过不了;或者依赖加了但版本冲突被排除掉了,编译过了,运⾏时静默失效。

6.2 @Resource 不是"纯按名字"

⽹上流传最⼴的那句" @Resource 按名字注⼊, @Autowired 按类型注⼊",只说对了⼀半。真实逻辑在这⾥:

// [framework] .../annotation/CommonAnnotationBeanPostProcessor.java:548

if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {
autowiredBeanNames = new LinkedHashSet<>();
resource = autowireCapableBeanFactory.resolveDependency(
element.getDependencyDescriptor(), requestingBeanName, autowiredBeanNames, null);
if (resource == null) {
throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
}
}
else {
resource = autowireCapableBeanFactory.resolveBeanByName(name, element.getDependencyDescriptor());
autowiredBeanNames = Collections.singleton(name);
}

fallbackToDefaultTypeMatch 默认 true ( :169 )。所以完整语义是:

名字优先;只有当(你没显式写 name )且(容器⾥确实没有这个名字的 bean)时,才退化成按类型解析。

三个条件缺⼀不可。第三个条件才是关键,也正是⽹⽂普遍漏掉的那个。

6.3 同⼀件事,两种脾⽓现在把 §5 末尾埋的那条对⽐拉出来。同样是"注解打在 static 成员上"这件事:

@Autowired @Resourcestatic 字段

logger.info(...) 后 return

[framework].../annotation/AutowiredAnnotationBeanPostProcessor.java:562

throw new IllegalStateException("@Resource annotation is not supported on static
fields")

[framework] .../annotation/CommonAnnotationBeanPostProcessor.java:416static ⽅法

logger.info(...) 后 return

同⽂件 :580

throw new IllegalStateException(...)

同⽂件 :443⼀个只记⽇志,⼀个直接把应⽤启动⼲掉。 两个处理器,⼀份⼼智模型,两种失败模式。

这是本章第⼆处必须批评的地⽅。这个不⼀致没有任何技术上的必然性—— @Resource 是 Jakarta 规范的注解、Spring 决定严格照规范办, @Autowired 是 Spring ⾃家的、于是宽容⼀点——这个解释在框架内部说得通,但对使⽤者来说毫⽆意义。使⽤者的⼼智模型是"注⼊注解",不是"哪个规范定义的注⼊注解"。结果就是:把 @Autowired 误写在 static 字段上的⼈,会经历⼀次默默的 NPE 排查;把 @Resource 误写在 static 字段上的⼈,会得到⼀条清清楚楚的启动期报错。后者的体验明显更好,⽽这纯属运⽓。

6.4 两⾏ addAll ,造出两个相反的⽅向@PostConstruct 和 @PreDestroy 的执⾏顺序,全部藏在 buildLifecycleMetadata 的这两⾏⾥:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java:314

initMethods.addAll(0, currInitMethods); //头插 →⽗类的 init先跑
destroyMethods.addAll(currDestroyMethods); //尾追 →⼦类的 destroy先跑

外层是⼀个从⼦类逐层向上到 Object 的 do...while ( :316-318 )。头插的那⼀列,最后变成"⽗类在前";尾追的那⼀列,保持"⼦类在前"。

init 是从⽗到⼦,destroy 是从⼦到⽗,两个⽅向相反。 这与构造/析构的直觉⼀致,⽽实现它只⽤了两个 addAll 的不同重载。这两⾏是我在整个 BPP 家族⾥最喜欢的两⾏代码。

🦴 顺带两条: @PostConstruct 是在 postProcessBeforeInitialization ⾥执⾏的( :213-226 ),也就是在 afterPropertiesSet 之前;⽽ destroy ⽅法抛异常只

WARN 不抛( :233-253 ,⽂案是 "Destroy method on bean with name '…' threw an exception")。还有⼀条常被误解的:javadoc 明说 "Init and destroy annotations maybe applied to methods of any visibility: public, package-protected, protected, or private."( :67-68 )——私有⽅法上的 @PostConstruct 是有效的。

七、这⼀排⼈,是怎么排队的最后⼀个问题:这么多"过⼿的⼈",谁先谁后?

答案分两半:注册的时机决定⼤局,排序接⼝决定局部。

7.1 refresh ⾥的两⾏[framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java

:596 prepareBeanFactory(beanFactory); ← 硬编码塞进三个
:604 invokeBeanFactoryPostProcessors(beanFactory); ← 上⼀章:改图纸的⼈
:606 registerBeanPostProcessors(beanFactory); ← 本章的⼈在这⾥统⼀登场
:622 finishBeanFactoryInitialization(beanFactory); ← ⾮懒单例在这⾥被造出来

prepareBeanFactory ⾥ new 出来硬塞的有三个: ApplicationContextAwareProcessor ( :737 )、 ApplicationListenerDetector ( :754 ,注释写着 "Registerearly post-processor…")、以及条件性的 LoadTimeWeaverAwareProcessor ( :757-761 ,条件是⾮ native image 且容器⾥存在 loadTimeWeaver bean)。

这三个不是 bean,是直接 new 的。 记住这点,7.3 要⽤。

7.2 ⼀段写给未来 PR 作者的警告registerBeanPostProcessors 的⽅法体⼀开头,挂着 Spring 全仓最不寻常的⼀段注释:

// [framework] spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java:214// WARNING: Although it may appear that the body of this method can be easily// refactored to avoid the use of multiple loops and multiple lists, the use// of multiple lists and multiple passes over the names of processors is// intentional. We must ensure that we honor the contracts for PriorityOrdered// and Ordered processors. Specifically, we must NOT cause processors to be

// instantiated (via getBean() invocations) or registered in the ApplicationContext

// in the wrong order.//

// Before submitting a pull request (PR) to change this method, please review the

// list of all declined PRs involving changes to PostProcessorRegistrationDelegate// to ensure that your proposal does not result in a breaking change:

// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22

⼀段注释,附带⼀条"被拒绝的 PR 列表"的搜索链接。

我很想把这段夸成"⼯程⾃律的典范",但诚实地说,它同时是⼀份认罪书。这段代码需要⽤⼀条链接来劝退好⼼⼈,恰恰说明:"BPP 的注册顺序"这件事,从来没有被显式建模成⼀个数据结构或⼀个不变式,⽽是被编码在了"四个 list、三轮遍历、两次重注册"的执⾏流程⾥。 意图藏在流程⾥,不在类型⾥。任何⼀个读代码的⼈第⼀反应都是"这能合并成⼀个循环吧"——因为代码本身没有任何东⻄在阻⽌他这么想。⽤注释拦住重构,是在承认结构没能表达约束。

那么这六步到底在⼲什么?

① 按类型取名字,但不实例化

String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

:227 —— 第三个参数 allowEagerInit = false ,这是不触发提前实例化的关键。

② 先装⼀个"举报器"( :232-234 ): BeanPostProcessorChecker ,下⾯ 7.4 细说。

③ 分三桶( :242-256 ): isTypeMatch(ppName, PriorityOrdered.class) 进第⼀桶并⽴刻 getBean 实例化( :244 );否则 isTypeMatch(ppName, Ordered.class)

进第⼆桶(只记名字);剩下的进第三桶(只记名字)。同时凡是 MergedBeanDefinitionPostProcessor 的,另外抄⼀份进 internalPostProcessors ( :246-248 、 :267-269 、 :279-281 )。

④ 依次注册:第⼀桶排序后注册( :259-260 );第⼆桶逐个 getBean → 排序 → 注册( :263-272 );第三桶逐个 getBean → 不排序 → 注册( :275-283 ,对⽐⼀下就会发现 :283 前⾯确实没有 sortPostProcessors )。

⑤ 把 internal 那批重新注册⼀遍( :285-287 )。

⑥ 再 new ⼀个 ApplicationListenerDetector 注册⼀遍( :289-291 ),注释解释了理由:"moving it to the end of the processor chain (for picking up proxies

etc)"——它必须看到被代理之后的对象,才能正确判断"这玩意⼉到底是不是 ApplicationListener "。

第 ⑤ ⑥ 步看起来很怪:已经注册过的东⻄,为什么要再注册⼀遍? 答案在 addBeanPostProcessor 的实现⾥:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java:981

public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
synchronized (this.beanPostProcessors) {

// Remove from old position, if any

this.beanPostProcessors.remove(beanPostProcessor);

// Add to end of list

this.beanPostProcessors.add(beanPostProcessor);
}
}

这不是防重复,这是⼀个"把它挪到队尾"的原语。 整个六步编排都建⽴在这个语义上:重复注册 = 移到最后 = 最晚执⾏。

7.3 @Order 对 BeanPostProcessor ⽆效——原因是双重的

javadoc ⽩纸⿊字:

"Furthermore, the @Order annotation is not taken into account for BeanPostProcessor beans." [framework] .../config/BeanPostProcessor.java:56-57源码上是两条互相独⽴的原因:

1. 分桶只认接⼝。 :243 和 :250 ⽤的是 isTypeMatch(ppName, PriorityOrdered.class) / isTypeMatch(ppName, Ordered.class) 。⼀个只打了 @Order 却不

实现 Ordered 的 BPP,会落进第三桶——⽽第三桶根本不排序。

  1. 即使侥幸进了排序桶也轮不到注解。 排序器在注解驱动的容器⾥是 AnnotationAwareOrderComparator.INSTANCE (设置点在 [framework].../annotation/AnnotationConfigUtils.java:148-150 ),⽽它的 findOrder 是这样的:

// [framework] spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java:63

protected @Nullable Integer findOrder(Object obj) {
Integer order = super.findOrder(obj); // ←先看 Ordered接⼝
if (order != null) { return order; } // ←⾮ null就直接返回,压根不看注解
return findOrderFromAnnotation(obj);
}

同⼀段 javadoc 还藏着另⼀条同样重要、但知名度低得多的规则:

" BeanPostProcessor beans that are registered programmatically with a BeanFactory will be applied in the order of registration; any ordering semantics

expressed through implementing the PriorityOrdered or Ordered interface will be ignored" [framework] .../config/BeanPostProcessor.java:50-55这就解释了 7.1 那个悬念: ApplicationContextAwareProcessor 没实现任何排序接⼝,凭什么能稳稳排在最前?因为它是 prepareBeanFactory ⾥addBeanPostProcessor 直接塞进去的——编程式注册,先来先到。

7.4 排队的实测结果把本基线各家的 order 值查出来(值越⼩越靠前):

BPP order 值 坐标ConfigurationPropertiesBindingPostProcessor HIGHEST_PRECEDENCE + 1[boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindinauto-proxy creator Ordered.HIGHEST_PRECEDENCE[framework] spring-aop/src/main/java/org/springframework/aop/config/AopConfigUtils.java:139order 属性)

PersistenceAnnotationBeanPostProcessor LOWEST_PRECEDENCE - 4[framework] spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessorCommonAnnotationBeanPostProcessor LOWEST_PRECEDENCE - 3 [framework] .../annotation/CommonAnnotationBeanPostProcessor.java:191AutowiredAnnotationBeanPostProcessor LOWEST_PRECEDENCE - 2 [framework] .../annotation/AutowiredAnnotationBeanPostProcessor.java:172InitDestroyAnnotationBeanPostProcessor Ordered.LOWEST_PRECEDENCE [framework] .../annotation/InitDestroyAnnotationBeanPostProcessor.java:114ProxyProcessorSupport (AOP 那批的基类默认) Ordered.LOWEST_PRECEDENCE [framework] spring-aop/src/main/java/org/springframework/aop/framework/ProxyProcessorSuppor⼀条可以直接背下来的结论: @PersistenceContext (-4)→ @Resource (-3)→ @Autowired (-2)。注⼊顺序是确定的, @Resource 跑在 @Autowired 前⾯。

⚠ ⽽ auto-proxy creator 的位置带来⼀条更重要的推论:它排在 HIGHEST_PRECEDENCE ,⽽ @Autowired / @Resource 那批(都是

MergedBeanDefinitionPostProcessor )在第 ⑤ 步被挪到了队尾。所以排在 auto-proxy 之后的每⼀个 BPP,在 postProcessAfterInitialization ⾥拿到的都是代理对象,不是原件。 任何想读⽬标类注解的下游 BPP 都得⾃⼰脱⼀层壳,⽐如:

// [framework] spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java:287

Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);

这⼀⾏不是可选的防御性编程,是必需品。在 CGLIB ⽣成的⼦类上找注解,结果和在⽤户类上找并不⼀样。

7.5 那条谁都⻅过的 WARN// [framework] .../support/PostProcessorRegistrationDelegate.java:414

public Object postProcessAfterInitialization(Object bean, String beanName) {
if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {

... warn ...

}
return bean;
}

三个豁免条件:你⾃⼰就是 BPP、你是 ROLE_INFRASTRUCTURE 、BPP 已经全注册完了。都不满⾜,就吃这条 WARN:

"Bean '…' is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly

injected/applied to a currently created BeanPostProcessor …? … If this bean does not have to be post-processed, declare it with ROLE_INFRASTRUCTURE."

它甚⾄能识别最常⻅的那个具体病因,给出针对性提示:

"The currently created BeanPostProcessor […] is declared through a non-static factory method on that class; consider declaring it as static instead."

[framework] .../support/PostProcessorRegistrationDelegate.java:429-433根因是⼀个鸡⽣蛋的死结:BPP 必须在所有普通 bean 之前被造出来;⽽⼀个⾮ static 的 @Bean ⽅法要被调⽤,得先把它所在的 @Configuration 类实例化;那个配置类⼀旦被提前实例化,它⾥⾯的其它 bean(以及那些 bean 的依赖)就赶在 BPP 注册完之前出⽣了——于是它们错过了后⾯才注册的那些"过⼿的⼈",包括 auto-proxycreator。它们的 @Transactional 是⽆效的,⽽且没有任何异常。

官⽅处⽅写在 @Bean 的 javadoc ⾥,有⼀整节⼩标题就叫 " BeanPostProcessor -returning @Bean methods"( [framework] spring-context/src/main/java/org/springframework/context/annotation/Bean.java:202-225 ):把返回 BPP 的 @Bean ⽅法标成 static ,⽽且最好⼀个依赖都别声明。

Boot 侧有⼀个把这套规矩执⾏得⾮常到位的样板:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBindingPostProcessor.java:69

public void afterPropertiesSet() throws Exception {

// We can't use constructor injection of the application context because// it causes eager factory bean initialization

this.registry = (BeanDefinitionRegistry) this.applicationContext.getAutowireCapableBeanFactory();
this.binder = ConfigurationPropertiesBinder.get(this.applicationContext);
}

它刻意不⽤构造器注⼊ ApplicationContext ,改成 ApplicationContextAware + afterPropertiesSet 两段式,注释把理由写死在代码⾥。⽽且它的注册⽅式是静态⽅

法 + definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE) (同⽂件 :114-124 , setRole 在 :120 )——正好对上 7.5 开头那三个豁免条件⾥的第⼆条。

顺带三条关于它的事实:它的 order 是 HIGHEST_PRECEDENCE + 1 ( :78 ),⼏乎排在最前;它在 BeforeInitialization ⾥做绑定( :82-87 ),所以你的 @PostConstruct ⾥能读到已经绑好的属性值。这两条合起来解释了 @ConfigurationProperties 为什么"总是先于⼀切就绪"。

🦴 ⻣灰级细节

⼀张会⾃⼰失效的 List。 容器每造⼀件器都要按类型分别遍历这⼏种 BPP,如果每次都 instanceof 过⼀遍全表,代价太⾼。于是 AbstractBeanFactory 维护了两样东⻄:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java:154

private final List<BeanPostProcessor> beanPostProcessors = new BeanPostProcessorCacheAwareList();

// :157

private @Nullable BeanPostProcessorCache beanPostProcessorCache;
BeanPostProcessorCacheAwareList ( :2020 , @since 5.3 )是 CopyOnWriteArrayList 的私有⼦类,它覆盖了 set / add / add(int) / remove(int) /
remove(Object) / removeAll / retainAll / addAll / addAll(int) / removeIf / replaceAll 共 11 个变更⽅法,每⼀个都在改完之后调

resetBeanPostProcessorCache() ——⽽后者只是把缓存字段置 null ( :1049-1053 ),下次访问时懒重建。⽤继承把"缓存失效"这件事焊死在数据结构上,⽽不是指望每个调⽤点记得⼿动清。

缓存本身是四张预筛表( :2116 , @since 5.3 ): instantiationAware / smartInstantiationAware / destructionAware / mergedDefinition 。构建逻辑在

getBeanPostProcessorCache() ( :1024-1047 )。注意 smartInstantiationAware 是嵌套在 instantiationAware 的 if ⾥⾯加的( :1030-1035 )——所以 Smart

的⼀定同时在 instantiationAware 表⾥,⽽每张表的顺序都严格等同于主表的顺序。

销毁时也不空转。 DisposableBeanAdapter 在构造时就按 requiresDestruction(bean) 把⽆关的 BPP 过滤掉⼀次( [framework]
.../support/DisposableBeanAdapter.java:482-495 ),销毁时只遍历筛过的那批。⽽ requiresDestruction(Object) 的默认实现是返回 true

( .../config/DestructionAwareBeanPostProcessor.java:57-59 , @since 4.3 )——它是这个家族⾥唯⼀⼀个默认值"多做⼀点"⽽不是"什么都不做"的⽅法,因为漏掉⼀次销毁⽐多问⼀次代价⼤。

⚠ 暗礁清单

暗礁 坐标(均为 [framework] )

1postProcessBeforeInstantiation 返回⾮ null → 只⾛ afterInitialization,跳过属性填充、初始化回调、销毁注册.../support/AbstractAutowireCapableBeanFactory.java:512-517 、 :1131-11342beforeInstantiationResolved 记住"没⼈接管",后加的 BPP 对⽼图纸⽆效同上 :1126 、 :11373postProcessAfterInstantiation 返回 false → 整个 populateBean 返回,所有注⼊作废同上 :1416-14224postProcessBeforeInitialization返回 null → 静默中断后续 BPP(AOP悄悄消失,⽆任何⽇志)

同上 :424-4325@Order 对 BPP ⽆效(分桶只认接⼝ +第三桶不排序 + ⽐较器先看接⼝)

.../config/BeanPostProcessor.java:56-57 ; .../support/PostProcessorRegistrationDelegate.java:243 、 :250 、 :283 ; spring-core/.../AnnotationAwareOrderComparator.java:63-696编程式注册的 BPP 完全忽略 Ordered /PriorityOrdered ,只按注册顺序.../config/BeanPostProcessor.java:50-557auto-proxy 之后的 BPP 拿到的是代理,必须⾃⼰ ultimateTargetClass 脱壳.../scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java:287

暗礁 坐标(均为 [framework] )

8⾮ static 的 @Bean BPP ⽅法 → 声明它的 @Configuration 类被提前实例化,其中的 bean 失去完整后处理.../annotation/Bean.java:202-225 ;WARN ⽂案 .../support/PostProcessorRegistrationDelegate.java:429-4429prototype bean 不注册销毁回调,@PreDestroy 永不调⽤.../support/AbstractBeanFactory.java:193610@Autowired 打在 static 上只 INFO 静默失效; @Resource 打在 static 上直接IllegalStateException.../annotation/AutowiredAnnotationBeanPostProcessor.java:562 、 :580 ; .../annotation/CommonAnnotationBeanPostProcessor.java:4111record 类型的 bean 整个跳过属性填充阶段.../support/AbstractAutowireCapableBeanFactory.java:1402-141112isSynthetic 守卫不对称:synthetic 图纸跳过四类回调,但仍⾛postProcessProperties有守卫 :1128 、 :968 、 :1416 、 :656 、 :1806 、 :1817 ;⽆守卫 :143913缺 jakarta.annotation 依赖 →CommonAnnotationBeanPostProcessor根本不注册, @PostConstruct 静默失效.../annotation/AnnotationConfigUtils.java:119-120 、 :170-174🎯 三句带⾛1. BeanPostProcessor 的两个⽅法返回 Object ⽽不是 void ,所以每⼀道⼝⼦都是掉包点——AOP 就是 AbstractAutoProxyCreator 在postProcessAfterInitialization ⾥ return proxy ( [framework] spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java:341 ),此外没有任何魔法。

  1. @Order 对 BeanPostProcessor ⽆效,必须实现 PriorityOrdered / Ordered 接⼝;⽽编程式 addBeanPostProcessor 注册的连接⼝都不看,纯按注册顺序,且该⽅法的语义是"先 remove 再 add 到队尾"。
  1. 返回 null 不等于"这个 bean 是 null",等于"这条链到此为⽌"——链⼀断,排在后⾯的 auto-proxy creator 就不会执⾏,代理静默消失,没有任何⽇志。

承上启下这⼀章我们看清了⼀件事:容器造⼀件器的过程中,开了⼗⼀道⼝⼦给外⼈插⼿,其中好⼏道⼝⼦上的⼈有权把⼿⾥的东⻄换掉。

但正是这个"能换掉"的权⼒,制造了⼀个⾮常尴尬的局⾯。

回头看时机 D 那⼏⾏——当 A 依赖 B、B ⼜依赖 A 时,容器必须在 A 还没完⼯的时候,就把 A 的引⽤先递给 B。问题是:递哪⼀个 A?

递原件?可 A 最终会被 auto-proxy creator 换成代理,那 B ⼿⾥攥着的就是个过期的原件—— doCreateBean ⾥那条著名的 BeanCurrentlyInCreationException( [framework] .../support/AbstractAutowireCapableBeanFactory.java:618-634 )就是为这⼀刻准备的:"…has been injected into other beans […] in its rawversion as part of a circular reference, but has eventually been wrapped."

递代理?可这时候还不知道 A 到底需不需要代理—— getAdvicesAndAdvisorsForBean 得跑⼀遍才知道,⽽这⼀跑就是实打实的开销,凭什么每个 bean 都付?

于是容器给出了⼀个折中⽅案:先不递对象,递⼀个"你真来要的时候我再决定给什么"的⼯⼚。

这就是三级缓存⾥那神秘的第三级——它存的不是对象,是 ObjectFactory 。下⼀章 ch11,我们把这三级缓存⼀级⼀级掀开,看清"半成品先递出去"这套机制到底解决了什么、⼜留下了什么解不了的死⻆——⽐如那个⼆⼗年没解决、也解不了的构造器注⼊循环依赖。