源码小说CodeStory
登录
上一章

39,040 字 · 约 98 分钟

下一章
字体

主题

版式

第8章 卷二 · 图纸 · 开造之前先改图纸

开造之前先改图纸"我不是来改你的图纸的。绝⼤多数图纸,是我画的。" —— ConfigurationClassPostProcessor 的⾃⽩开场:⼀段⼈⼈写过、却没⼈说得清的代码@Configuration

class Cfg {
@Bean A a() { return new A(b()); } // ←这⾥调了⼀次 b()
@Bean B b() { return new B(); } // ←容器也会调⼀次 b()
}

按 Java 语⾔规范, b() 是个再普通不过的实例⽅法调⽤。两次调⽤,两个 new B() ,两个对象。这是编译器的承诺,是 JLS 写死的东⻄。

但你把这段代码丢进 Spring, ctx.getBean(A.class).b 和 ctx.getBean(B.class) 是同⼀个对象。

Java 没有骗你,是有⼈在中间动了⼿脚。⽽这个⼿脚动得极其隐蔽:它不改你的源码,不要求你写任何额外注解,甚⾄不在你的类⾥留下任何可⻅痕迹——除⾮你去看运⾏时的字节码,才会发现你的配置类多了⼀个你从来没写过的 public 字段。

这⼀章就是拆这个⼿脚。但要拆它,得先说清楚它发⽣在什么时候——发⽣在图纸都画完了、实物还⼀件没造的那个窗⼝⾥。这个窗⼝,在 refresh() 的第 604 ⾏。

⼀、 refresh() ⾥那道冻结线先把坐标钉死。

// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java

582 public void refresh() throws BeansException, IllegalStateException {
593 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //图纸库就位
604 invokeBeanFactoryPostProcessors(beanFactory); // ←本章主战场
606 registerBeanPostProcessors(beanFactory);
622 finishBeanFactoryInitialization(beanFactory); //到这⾥才真正造单例

:593 到 :604 之间,图纸库⾥已经有了⼀批图纸; :622 之后,作坊开始照图施⼯。中间夹着的 :604 ,就是这本书⾥最重要的⼀条冻结线——冻结前你可以随便改图纸,冻结后只准照做。

invokeBeanFactoryPostProcessors ⾃⼰⼀⾏正事没⼲,⼀句话就转⼿了:

// [framework] .../support/AbstractApplicationContext.java:795-796

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
}

真正的活在 PostProcessorRegistrationDelegate ⾥。我们待会⼉再进去——先认⼈。

⼆、两个接⼝,⼀条不许交换的顺序2.1 改图纸内容的⼈

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/config/BeanFactoryPostProcessor.java:69-80@FunctionalInterface

public interface BeanFactoryPostProcessor {
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}

⼀个⽅法,⼀个参数。 @since 06.07.2003 ——这个古早的⽇期格式本身就是⽂物,说明这接⼝跟 Spring 差不多⼀样⽼。

它的红线写在 javadoc ⾥,措辞相当严厉( :31-35 ):

A BeanFactoryPostProcessor may interact with and modify bean definitions, but never bean instances. Doing so may cause premature bean instantiation,violating the container and causing unintended side effects.翻译成坊⾥话:你可以改图纸上的字,但绝不许提前照着造出实物来。你⼀造,那件器就绕过了后⾯所有还没排上队的⼯序——它没被后来的 BFPP 改过图纸,也没被 BPP 过过⼿,出来就是个半残品。

2.2 改图纸⽬录的⼈// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionRegistryPostProcessor.java:34-54

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {
void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

/** @since 6.1 */@Override

default void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
}

先记⼀个特别容易记错的事:这两个接⼝不在同⼀个包。 BeanFactoryPostProcessor 在 beans.factory.config , BeanDefinitionRegistryPostProcessor 在beans.factory.support ( :17 )。原因很实在——后者依赖 BeanDefinitionRegistry ,⽽那是 support 包的东⻄。⼀个"接⼝该放哪个包"的决定,被依赖⽅向拽⾛了。

差别是能⼒上的:BFPP 拿到的是 ConfigurableListableBeanFactory ,只能对已经在册的图纸改字;BDRPP 拿到的是 BeanDefinitionRegistry ,能往图纸库⾥加新图纸、能撤掉旧图纸。它的 javadoc( :24-28 )说得很直⽩:允许在常规 BFPP 探测启动之前注册更多 bean definition,⽽这些新 definition 本身还可以定义出新的 BFPP。

那个 @since 6.1 的 default 空实现值得单独提⼀句:6.1 之前,你写 BDRPP 必须实现两个⽅法,哪怕第⼆个你压根不关⼼。这个"多余的空⽅法"在 Boot 仓⾥⾄今还留着化⽯——⽐如 [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java:102-104 那个空得⼲⼲净净的postProcessBeanFactory 。代码不会撒谎,它只是懒得删。

2.3 顺序铁律所有 BDRPP 的 postProcessBeanDefinitionRegistry 全部跑完,才轮到任何⼀个 postProcessBeanFactory 。

这不是"建议顺序",是不变量。理由⽤反证法⼀句话说完:如果允许某个 BFPP 在 postProcessBeanFactory 阶段还往 registry ⾥塞新图纸,那前⾯那些声称"我已经遍历处理了所有 bean definition"的 BFPP 就全都撒了谎——它们漏掉了后来的。⼀个"我处理了全部"的承诺,要求集合在处理期间不能增⻓。

三、那段劝退注释,和它守着的⼗步PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors ⽅法体⼀进⻔就贴了⼀张告示:

// [framework] spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java:71-82// 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=...label%3A%22status%3A+declined%22

"这段丑代码是故意丑的。改之前先去看看被拒掉的那⼀⻓串 PR。"

同样的告示在 :214-225 ⼜复制了⼀遍(守 registerBeanPostProcessors )。整个 Spring ⾥这么写注释的地⽅屈指可数。

我先把批评摆在这⼉:⼀段代码需要靠"请先阅读历史上所有被拒 PR"来⾃我保护,说明它的约束没有被结构化地表达出来——不变量全在⼈的脑⼦⾥和注释⾥,⼀条都没落到类型系统或断⾔上。这段注释是设计债的⾃供状,只不过 Spring 团队⾜够诚实,把⽋条贴在了⻔⼝。诚实值得敬重,但⽋条终究是⽋条。

告示后⾯那 140 ⾏,展开来是⼗步。我按执⾏先后列⼀遍(⾏号均在同⼀⽂件):

Phase A —— 仅当 beanFactory 同时是 BeanDefinitionRegistry(:87)

  1. 编程式注册的 BDRPP.postProcessBeanDefinitionRegistry :91-99 ← 不排序,就按注册顺序2. PriorityOrdered 的 BDRPP bean :107-119 ← CCPP 在这⼀梯队3. Ordered 的 BDRPP bean :121-1324. 其余 BDRPP bean,while 循环到不再冒出新的 :134-1505. 上述所有 BDRPP 的 .postProcessBeanFactory :152-154 ← CGLIB 增强在这⾥发⽣紧接着编程式注册的普通 BFPP :154Phase B —— 普通 BFPP bean(:162-204)
  1. 三分桶:已处理的跳过 / PriorityOrdered / Ordered / ⽆序 :169-1857. PriorityOrdered 桶 :187-189
  1. Ordered 桶 :191-1979. ⽆序桶 :199-204
10. beanFactory.clearMetadataCache() :208

有⼏处细节,不逐字读源码是绝对看不出来的。

其⼀,第 4 步的 while 是个不动点循环。

// :134-150

boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}

// ... sort → invoke → clear

}

这是"画图员可以画出新的画图员"的闭环。⼀个 BDRPP 往图纸库⾥注册了另⼀个 BDRPP 的图纸,下⼀轮 getBeanNamesForType 就会捞到它,照样执⾏。收敛条件是"这⼀轮没发现新⾯孔"。

其⼆, getBeanNamesForType 的第三个参数⼀直是 false 。

// :162-165// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let the bean factory post-processors apply to them!

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

那个 false 是 allowEagerInit 。意思是:为了做类型判断,绝不允许把 FactoryBean 提前造出来问它 getObject() 返回什么类型。这是"改图纸阶段不许造实物"这条红线在实现层⾯的具体守法动作。

其三,⼀个极精巧、极容易被读漏的分桶细节。

看 :176-183 :

else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); //⽴刻 getBean
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName); //只存名字
}
else {
nonOrderedPostProcessorNames.add(ppName); //只存名字
}

PriorityOrdered 桶在分类时就 getBean 实例化了,⽽ Ordered 桶和⽆序桶只先记下名字,等到⾃⼰那⼀轮才去 getBean ( :193-195 、 :201-203 )。

为什么?因为 PriorityOrdered 的那批⻢上就要跑,它们跑的时候可能会去改后⾯那些 BFPP ⾃⼰的 bean definition。如果⼀开始就把所有 BFPP 全实例化了,那些改动就⽩改了——图纸改了,可器已经照旧图造完了。推迟实例化到最后⼀刻,是为了让"改图纸的⼈"也能被别⼈改图纸。这就是那段劝退注释守着的核⼼不变量之⼀。

其四,⼀个我认为值得记⼀辈⼦的不对称。看 :199-204 :

// Finally, invoke all other BeanFactoryPostProcessors.

List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

前两桶都有 sortPostProcessors(...) ,唯独⽆序桶这⼀⾏没有。合理——它们本来就没声明顺序,排什么?但后果是:⽆序 BFPP 的实际执⾏顺序 =getBeanNamesForType 的返回顺序 = 注册顺序。它是确定的,但这份确定性没有任何契约保护你。哪天你换了个扫描顺序,它就变了。

3.1 ⚠ 第⼀块暗礁:那个"写了也没⽤"的 order回到第 1 步, :91-99 :

for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor registryProcessor) {
registryProcessor.postProcessBeanDefinitionRegistry(registry); //⽴刻执⾏,不排序
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}

⼀个 sort 都没有。这正是 BeanFactoryPostProcessor javadoc ⾥那段警告( :50-61 )的落地处:

... BeanFactoryPostProcessor beans that are registered programmatically with a ConfigurableApplicationContext will be applied in the order of registration;

any ordering semantics expressed through implementing the PriorityOrdered or Ordered interface will be ignored for programmatically registered post-processors. Furthermore, the @Order annotation is not taken into account for BeanFactoryPostProcessor beans.三句话,三个坑:

1. 编程式注册的( context.addBeanFactoryPostProcessor(...) )→ PriorityOrdered / Ordered ⼀律被忽略,只认注册顺序;
  1. @Order 注解对 BFPP bean 完全不⽣效——只认接⼝,不认注解。这条尤其反直觉,因为 Spring ⽣态⾥ @Order ⼏乎处处能⽤,偏偏这⾥不⾏;
  1. 只有被容器⾃动探测成 bean 的那批,排序才算数。

现成的反讽就在 Boot 仓⾥。 [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/SharedMetadataReaderFactoryContextInitializer.java :

// :87-100static class CachingMetadataReaderFactoryPostProcessor

implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {

@Override

public int getOrder() {

// Must happen before the ConfigurationClassPostProcessor is created

return Ordered.HIGHEST_PRECEDENCE;
}

它郑重其事地实现了 PriorityOrdered ,返回最⾼优先级,还写了注释解释"必须在 CCPP 之前发⽣"。但它是在 initialize() ⾥⽤

applicationContext.addBeanFactoryPostProcessor(postProcessor) 编程式注册的( :68-69 )——按契约,这个 order 被完整地忽略了。

它之所以确实跑在 CCPP 前⾯,跟 order ⼀点关系都没有,纯粹是因为 :91-99 让所有编程式 BDRPP ⽆条件先跑。

这个 getOrder() 是⽂档性的,不是功能性的。它准确地表达了作者的意图,也准确地误导了每⼀个读代码的⼈。我不认为这是 Boot 的错——⼀个接⼝既定义了 order ⼜在某些注册路径下静默丢弃 order,这个契约本身就是有毒的。你没法在编译期发现它,也没法在运⾏期发现它,只能靠读 javadoc ⾥那三⾏字。

四、CCPP:它不改图纸,它画图纸现在请出这⼀层最重的住户。

// [framework] spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java:152-154public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,BeanRegistrationAotProcessor, BeanFactoryInitializationAotProcessor, PriorityOrdered,

ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {

⼋个接⼝。⽽它真正的分量在于:其他所有 BDRPP 是来改图纸的,只有它是来画图纸的。你写的每⼀个 @Bean 、每⼀个被 @ComponentScan 扫到的 @Service 、Boot 帮你装的每⼀个⾃动配置类——那⼏百上千张图纸,全出⾃它⼀个⼈的⼿。

4.1 "我要早,但我给同梯队让路"

// :209-212@Override

public int getOrder() {
return Ordered.LOWEST_PRECEDENCE; // within PriorityOrdered
}

这四⾏是我在这个类⾥最喜欢的地⽅。它是 PriorityOrdered (保证进第⼀梯队),但在第⼀梯队⾥排最后⼀名。

翻译成⼈话:"我必须很早——因为 @Bean 的图纸得在任何其他 BFPP 执⾏之前就位(javadoc :141-144 原⽂如此);但我也不想挡住同梯队那些真正需要抢在我前⾯做准备的⼈。"

Boot 的 CachingMetadataReaderFactoryPostProcessor 正是这份让路的受益者——它要在 CCPP 被创建之前,把⼀个共享的 CachingMetadataReaderFactory 注册好,再顺⼿往 CCPP 的 bean definition 上追加⼀条 propertyValues ,让 CCPP ⽤上这个共享缓存( :107-110 、 :121-151 )。⼀个 BDRPP 改另⼀个 BDRPP 的图纸——第 3步那个 while 循环存在的意义,在这⾥具体化了。

4.2 它是什么时候进的图纸库?

⽐你想的早得多:

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

if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
def.setSource(source);
beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
}

bean 名字是个写死的常量( :69-70 ): "org.springframework.context.annotation.internalConfigurationAnnotationProcessor" 。⽽registerAnnotationConfigProcessors 的调⽤点在 AnnotatedBeanDefinitionReader 的构造器⾥( [framework].../annotation/AnnotatedBeanDefinitionReader.java:90 )和 ClassPathBeanDefinitionScanner ⾥( :261 )。

也就是说: new AnnotationConfigApplicationContext(...) 这⼀⾏ new 还没返回,CCPP 的图纸就已经躺在库⾥了。它不是 refresh() 期间才冒出来的,它是开⻔就在的。

4.3 两个⽅法,两件事,各带⼀把幂等锁// :304-317 ——画图纸

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) { throw new IllegalStateException(...); }
if (this.factoriesPostProcessed.contains(registryId)) { throw new IllegalStateException(...); }
this.registriesPostProcessed.add(registryId);
processConfigBeanDefinitions(registry);
}

// :323-339 ——施⼯前上釉

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
int factoryId = System.identityHashCode(beanFactory);
if (this.factoriesPostProcessed.contains(factoryId)) { throw new IllegalStateException(...); }
this.factoriesPostProcessed.add(factoryId);
if (!this.registriesPostProcessed.contains(factoryId)) {

// BeanDefinitionRegistryPostProcessor hook apparently not supported...

processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory); // :334兜底
}
enhanceConfigurationClasses(beanFactory); // :337 ← CGLIB就在这
beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory)); // :338
}

🦴 ⻣灰级细节:两把锁⽤的是 System.identityHashCode(registry) ⽽不是 registry 对象本身(字段是两个 Set<Integer> , :188 、 :190 )。为什么?为了不持有对容

器的强引⽤。⼀个 post-processor 记住"我处理过哪些容器",如果直接存对象,这些容器就永远不会被 GC。存⼀个 int 就没这个问题——代价是理论上的哈希碰撞,⽽这个代价Spring 认了。

:331-335 那个兜底分⽀是历史遗留:万⼀宿主容器只认 BFPP 不认 BDRPP(⽐如某些⾮标准的容器实现),就在这个时候把解析补做掉。

4.4 主循环:⼀张会⾃我繁殖的图纸processConfigBeanDefinitions 的⼼脏是⼀个 do/while :

// :450-491

do {
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
this.reader.loadBeanDefinitions(configClasses); // :464中间模型 → BeanDefinition
alreadyParsed.addAll(configClasses);
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) { // :472图纸库变多了?

// :479-487把"新增的、且还没解析过的"塞回 candidates

}
}
while (!candidates.isEmpty()); // :491

为什么必须循环、不能⼀趟扫完?

因为注解配置模型是会⾃我繁殖的: @ComponentScan 扫出来的类,可能它⾃⼰⼜是个 @Configuration ; @Import 进来的类,可能⼜带着 @ComponentScan ; @Import⼀个 ImportSelector ,它可能⼜选出⼀批带 @Import 的类。解析产⽣新图纸,新图纸⼜要解析。这种结构只能不动点迭代,没有别的解法。

注意 :472 的收敛判据是图纸总数变多了没有——朴素但⾜够。

顺带记⼀处职责切分( ConfigurationClassParser 类注释 :89-91 ): parse 只负责把配置类的结构读成模型, loadBeanDefinitions 才负责把模型落成 BeanDefinition——唯⼀的例外是 @ComponentScan ,它必须在 parse 阶段就⽴刻注册。因为扫出来的东⻄还得继续参与解析,你不注册,下⼀轮就找不到它。

五、七件事:⼀个 @Configuration 类被拆成什么样doProcessConfigurationClass ( [framework] .../annotation/ConfigurationClassParser.java:305-405 )是全套解析的⻣架。⼀百⾏,⼲七件事:

处理什么 ⾏ 要点

1 成员(嵌套)类 :309-312 仅当本类被 @Component 元注解时才递归2 @PropertySource :314-325 Environment 不是 ConfigurableEnvironment 时,只打⼀条 INFO 就忽略3 @ComponentScan :327-361 先找直接声明的,找不到才退回找元注解上的;扫到就⽴刻注册并递归4 @Import :364 四条分⽀,⻅下节5 @ImportResource :366-376 解占位符后只登记不加载6 @Bean ⽅法 :378-385 收成 BeanMethod 模型

处理什么 ⾏ 要点

7 接⼝ default ⽅法 + ⽗类 :387-401 ⽗类名以 "java" 开头就停( :393 )

第 7 步的循环协议很省事: doProcessConfigurationClass 的返回值就是⽗类( :398 返回 sourceClass.getSuperClass() ),返回 null 表示爬到顶了。调⽤⽅⼀个do/while 就把继承链⾛完了。

5.1 @ComponentScan 的两处硬规则第⼀处, :327-337 的"先直接、后元注解":

Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScan.class, ComponentScans.class,
MergedAnnotation::isDirectlyPresent);

// Fall back to searching for @ComponentScan meta-annotations ...

if (componentScans.isEmpty()) {
componentScans = AnnotationConfigUtils.attributesForRepeatable(sourceClass.getMetadata(),
ComponentScan.class, ComponentScans.class, MergedAnnotation::isMetaPresent);
}

这解释了⼀个 Boot ⽤户天天遇到、却很少想清楚的现象: @SpringBootApplication 上元注解了⼀个 @ComponentScan ,可你只要在启动类上再显式写⼀个@ComponentScan("com.other") ,元注解那个就完全不⽣效了——不是合并,是覆盖。因为直接声明的⼀旦⾮空, isMetaPresent 那⼀轮根本不会执⾏。

第⼆处更硬, :339-345 :

if (!componentScans.isEmpty()) {
List<Condition> registerBeanConditions = collectRegisterBeanConditions(configClass);
if (!registerBeanConditions.isEmpty()) {
throw new ApplicationContextException(

"Component scan for configuration class [%s] could not be used with conditions in REGISTER_BEAN phase: %s"

.formatted(configClass.getMetadata().getClassName(), registerBeanConditions));
}

@ComponentScan 和 ConfigurationPhase.REGISTER_BEAN 阶段的 Condition 不能共存,直接抛异常。理由很⼲脆:扫描发⽣在 PARSE 阶段,⽽ REGISTER_BEAN 条件此时还没到判定时机。这是 Spring 少⻅的"宁可炸也不静默"的地⽅——值得表扬,因为它的邻居就不这样。

5.2 邻居: @PropertySource 的静默失效// :318-324

if (this.propertySourceRegistry != null) {
this.propertySourceRegistry.processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}

propertySourceRegistry 是否为 null,取决于构造 parser 时 Environment 是不是 ConfigurableEnvironment ( :159-160 )。不是的话——你的 @PropertySource被完整地忽略了,全程只有⼀条 INFO 级⽇志。

绝⼤多数⽣产环境的⽇志级别是 INFO,所以你可能"看得到"。但你也可能在⼏万⾏启动⽇志⾥永远看不到它。同⼀个类⾥,⼀个约束选择 fail-fast 抛异常,另⼀个选择 INFO ⽇志放⾏,这个不⼀致本身就是坑。

5.3 @Import 的四条分⽀// :594-637(结构简化,分⽀条件为原⽂)

for (SourceClass candidate : importCandidates) {
if (candidate.isAssignable(ImportSelector.class)) { //分⽀ 1
ImportSelector selector = ParserStrategyUtils.instantiateClass(...);
Predicate<String> selectorFilter = selector.getExclusionFilter();
if (selectorFilter != null) { filter = filter.or(selectorFilter); } //过滤器沿链传递
if (selector instanceof DeferredImportSelector deferredImportSelector) {
this.deferredImportSelectorHandler.handle(configClass, deferredImportSelector); //排队
}
else {
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
processImports(configClass, currentSourceClass, asSourceClasses(...), filter, false); //⽴刻递归
}
}
else if (candidate.isAssignable(BeanRegistrar.class)) { //分⽀ 2(7.0新增)
BeanRegistrar registrar = (BeanRegistrar) BeanUtils.instantiateClass(candidateClass);

...

}
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) { //分⽀ 3
ImportBeanDefinitionRegistrar registrar = ParserStrategyUtils.instantiateClass(...);
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());

//注意:只登记,不执⾏

}
else { //分⽀ 4
this.importStack.registerImport(currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
processConfigurationClass(candidate.asConfigClass(configClass), filter);
}
}

分⽀ 1 和分⽀ 3 的时机差异,是理解整个 @Import 体系的钥匙:

ImportSelector 当场就问:"你要导⼊哪些类?"——因为它的产出还要继续参与解析;

ImportBeanDefinitionRegistrar 只登记不执⾏,真正的 registerBeanDefinitions 被推迟到 reader 阶段( [framework].../annotation/ConfigurationClassBeanDefinitionReader.java:423-428 )——因为它直接往图纸库写图纸,得等模型都稳定了再动⼿。

🦴 ⼀个必须记住的认知: ImportSelector 和 ImportBeanDefinitionRegistrar 都不是 bean。

看它们怎么被实例化的( [framework] .../annotation/ParserStrategyUtils.java:102-119 ):

private static @Nullable Object resolveParameter(Class<?> parameterType, ...) {
if (parameterType == Environment.class) { return environment; }
if (parameterType == ResourceLoader.class) { return resourceLoader; }
if (parameterType == BeanFactory.class) { return (registry instanceof BeanFactory ? registry : null); }
if (parameterType == ClassLoader.class) { return classLoader; }
throw new IllegalStateException("Illegal method parameter type: " + parameterType.getName());
}

构造器参数只⽀持这四种类型,第五种直接抛异常。⽽且只有"唯⼀构造器且有参"时才⾛这条路( :75-87 ),否则⼀律⽆参构造。之后回调 Aware 的顺序也是写死的:

BeanClassLoaderAware → BeanFactoryAware → EnvironmentAware → ResourceLoaderAware ( :121-139 )。

原因很朴素:它们要在容器还没成型的时候⼲活。这时候没有依赖注⼊可⽤,能递给它们的只有这四样"半成品"。你想在 ImportSelector ⾥ @Autowired ⼀个DataSource ?⻔都没有。

⚠ 还有⼀条容易踩的: ImportBeanDefinitionRegistrar 的 javadoc 在 :66-68 和 :92-94 两个地⽅重复写了同⼀句警告——

Note that BeanDefinitionRegistryPostProcessor types may not be registered here, due to lifecycle constraints related to @Configuration class processing.⼀句话在同⼀个⽂件⾥写两遍,通常意味着它被踩得够多。为什么不⾏?因为 registrar 执⾏的时候,BDRPP 那⼀轮正在跑。你这时候注册⼀个新的 BDRPP,虽然PostProcessorRegistrationDelegate 那个 while(reiterate) 确实会捞到它并执⾏,但它已经错过了⾃⼰本该排的位置——PriorityOrdered 和 Ordered 那两轮都已经过去了。语义上它迟到了,⽽迟到不报错。

5.4 为了顺序,宁可再读⼀遍 class ⽂件这⼀处我认为是全章最"教科书级"的⼯程决策。

// [framework] .../annotation/ConfigurationClassParser.java:459-470

private Set<MethodMetadata> retrieveBeanMethodMetadata(SourceClass sourceClass) {
AnnotationMetadata original = sourceClass.getMetadata();
Set<MethodMetadata> beanMethods = original.getAnnotatedMethods(Bean.class.getName());
if (beanMethods.size() > 1 && original instanceof StandardAnnotationMetadata) {

// 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 的标准反射返回⽅法的顺序是任意的——甚⾄同⼀台机器上同⼀个应⽤的两次运⾏都可能不同。

⽽ @Bean ⽅法的声明顺序会影响 bean 的注册顺序,注册顺序⼜会影响某些集合注⼊的顺序。于是 Spring 做了⼀件看起来很奢侈的事:当反射拿到超过⼀个 @Bean ⽅法时,额外⽤ ASM 把 class ⽂件再读⼀遍,按字节码⾥的声明顺序重排( :466-487 )。只有当"反射集合被 ASM 集合完全覆盖"时才采⽤重排结果( :483-486 ),读⽂件失败就静默回退到反射顺序( :489-492 )。

为确定性付出⼀次 I/O 的代价。但请注意这个兜底是静默的:万⼀ class ⽂件读不到(打包⽅式古怪、字节码被改写过),你会静默地退回到那个"任意顺序",⼀条 debug ⽇志都不⼀定看得⻅。这是⼀个把不确定性藏起来的兜底,不是消除它。

六、full 与 lite:两个字符串决定要不要上 CGLIB现在逼近爽点。第⼀个问题是:谁会被 CGLIB 增强?

答案藏在两个字符串⾥。

// [framework] spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java:55-57

static final String CONFIGURATION_CLASS_FULL = "full";
static final String CONFIGURATION_CLASS_LITE = "lite";

就是两个字符串。塞进 BeanDefinition 的 attribute ⾥(key 是 :70-71 的 CONFIGURATION_CLASS_ATTRIBUTE ),后⾯所有分⽀都看它。这是 Spring ⾥"⽤字符串标记跨阶段传递决策"的典型⼿法——省事,但也意味着没有类型系统帮你兜底。

判定发⽣在 checkConfigurationClassCandidate :

// :146-156

Map<String, @Nullable Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
else if (config != null || Boolean.TRUE.equals(beanDef.getAttribute(CANDIDATE_ATTRIBUTE)) ||
isConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
else {
return false;
}

⽽ isConfigurationCandidate ( :174-189 )给 lite 发了四张⻔票加⼀张兜底:

if (metadata.isInterface()) { return false; } //接⼝(含注解)直接出局
for (String indicator : candidateIndicators) { // :79-83
if (metadata.isAnnotated(indicator)) { return true; } // @Component/@ComponentScan/@Import/@ImportResource
}
return hasBeanMethods(metadata); //兜底:有没有 @Bean⽅法

🦴 ⼀处只有读源码才知道的⼩⼼思: :176 那句注释写的是 "Do not consider an interface or an annotation",但代码只判了 metadata.isInterface() 。因为注解在字节

码⾥本来就是接⼝,⼀个判断就把两种情况都盖住了。

回源核实的两条默认值:

@Configuration 的 proxyBeanMethods 默认是 true ( [framework] .../annotation/Configuration.java:477 )→ 默认落进 full。

⼀个只写了 @Component + ⼏个 @Bean ⽅法的类,是 lite,不会被增强。它的 @Bean ⽅法互调就是纯 Java 调⽤,调⼏次 new ⼏个对象。这是最经典的线上事故来源——代码看起来跟 @Configuration 那份⼀模⼀样,⾏为却完全不同。

6.1 ✨ 本基线的⼀处降级,很多⼈不知道然后是我在这⼀章⾥最想让你记住的⼀条版本性事实。

解析完之后,parser 会回头把 attribute 改⼀次:

// [framework] .../annotation/ConfigurationClassParser.java:183-189

// Downgrade to lite (no enhancement) in case of no instance-level @Bean methods.
if (!configClass.getMetadata().isAbstract() && !configClass.hasNonStaticBeanMethods() &&
ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(
bd.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE))) {
bd.setAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE,
ConfigurationClassUtils.CONFIGURATION_CLASS_LITE);
}

配套的判断( [framework] .../annotation/ConfigurationClass.java:211-218 ):

boolean hasNonStaticBeanMethods() {
for (BeanMethod beanMethod : this.beanMethods) {
if (!beanMethod.getMetadata().isStatic()) { return true; }
}
return false;
}

你写了 @Configuration (默认 full),但类⾥⼀个⾮ static 的 @Bean ⽅法都没有——包括"根本没有 @Bean ⽅法"这种情况——本基线会把它悄悄降级成 lite,完全跳过CGLIB。

这意味着⼀件事:⼀个最典型的 Boot 启动类@SpringBootApplication

public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }

@SpringBootApplication 链上是 @SpringBootConfiguration → @Configuration , proxyBeanMethods 默认 true ,看起来铁定是 full。但因为它⼀个实例级@Bean ⽅法都没有——在本基线下,它并不会被 CGLIB 增强。

所以,⽹上那句流传极⼴的"所有 @Configuration 类都会被 CGLIB 代理",在本基线上是错的。(本基线 = Framework 7.1.0-SNAPSHOT。⽣产上⼤多数⼈跑的是 6.x,⾏为请以你⾃⼰那个版本的源码为准——这正是我不敢替你下结论的地⽅。)

enhanceConfigurationClasses ⾥还有⼀层呼应( [framework] ConfigurationClassPostProcessor.java:531-533 ):lite 且没有 @Bean ⽅法的候选,连resolveBeanClass 都不做——能不加载类就不加载。

⚠ 这⾥有我对 Spring 的第⼆处批评:⼀个类到底会不会被增强,判定逻辑分散在⾄少三个地⽅—— ConfigurationClassUtils.checkConfigurationClassCandidate (初

判)、 ConfigurationClassParser 解析后的降级( :183-189 )、 enhanceConfigurationClasses ⾥的 containsSingleton 弃权( :549-557 )。三处都可能改变结论,且没有任何⼀处能单独回答"我这个类最终会不会被增强"。没有单⼀真相来源。你想搞清楚,只能三处都读⼀遍,或者上调试器看 bean 的 class 名字⾥有没有$$SpringCGLIB$$ 。

七、爽点:那个凭空⻓出来的 $$beanFactory现在拆开场那个⼿脚。

// [framework] spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java:63-70(类注释)

/**

* Enhances {@link Configuration} classes by generating a CGLIB subclass which
  • interacts with the Spring container to respect bean scoping semantics for
* {@code @Bean} methods. Each such {@code @Bean} method will be overridden in
* the generated subclass, only delegating to the actual {@code @Bean} method
  • implementation if the container actually requests the construction of a new
* instance. Otherwise, a call to such an {@code @Bean} method serves as a
  • reference back to the container, obtaining the corresponding bean by name.

*/

class ConfigurationClassEnhancer {

注意它是 package-private( :78 )——这么核⼼的⼀个类,Spring 从来没打算让你直接⽤。

7.1 三个 Callback,⼀个不存在的字段// :80-89// The callbacks to use. Note that these callbacks must be stateless.

static final Callback[] CALLBACKS = new Callback[] {
new BeanMethodInterceptor(), // 0:拦 @Bean⽅法
new BeanFactoryAwareMethodInterceptor(), // 1:拦 setBeanFactory

NoOp.INSTANCE // 2:其余放⾏

};
private static final ConditionalCallbackFilter CALLBACK_FILTER = new ConditionalCallbackFilter(CALLBACKS);
private static final String BEAN_FACTORY_FIELD = "$$beanFactory";

CALLBACKS 是 static final 且注释强调"必须⽆状态"——所有配置类共⽤同三个拦截器实例,⼀个应⽤⾥只有这三个对象。状态全在⽅法参数和 ThreadLocal ⾥。

然后是这⼀章最不为⼈知的⼀处精妙。那个 $$beanFactory 字段,你的源码⾥从来没有过,它是在 CGLIB ⽣成字节码的收尾阶段被硬插进去的:

// :281-298

private static class BeanFactoryAwareGeneratorStrategy extends ClassLoaderAwareGeneratorStrategy {

@Override

protected ClassGenerator transform(ClassGenerator cg) throws Exception {
ClassEmitterTransformer transformer = new ClassEmitterTransformer() {

@Override

public void end_class() {
declare_field(Opcodes.ACC_PUBLIC, BEAN_FACTORY_FIELD, Type.getType(BeanFactory.class), null);
super.end_class();
}
};
return new TransformingClassGenerator(cg, transformer);
}
}

在"类要封⼝了"的那⼀刻,插⼀个 public BeanFactory $$beanFactory 进去。

谁往⾥塞值? BeanFactoryAwareMethodInterceptor :

// :306-320

public @Nullable Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
Field field = ReflectionUtils.findField(obj.getClass(), BEAN_FACTORY_FIELD);
Assert.state(field != null, "Unable to find generated BeanFactory field");
field.set(obj, args[0]);
// Does the actual (non-CGLIB) superclass implement BeanFactoryAware?
// If so, call its setBeanFactory() method. If not, just exit.
if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) {
return proxy.invokeSuper(obj, args);
}
return null;
}

它拦下 setBeanFactory(BeanFactory) ,先把值反射写进那个凭空⻓出来的字段,然后只有当你的原类真的实现了 BeanFactoryAware 才继续往下调——否则直接返回,你的类完全不知道发⽣过什么。

⽽触发这次调⽤的,是 CCPP 在 postProcessBeanFactory 最后⼀⾏加进去的那个 BPP:

// [framework] ConfigurationClassPostProcessor.java:597-604

public @Nullable PropertyValues postProcessProperties(@Nullable PropertyValues pvs, Object bean, String beanName) {

// Inject the BeanFactory before AutowiredAnnotationBeanPostProcessor's// postProcessProperties method attempts to autowire other configuration beans.

if (bean instanceof EnhancedConfiguration enhancedConfiguration) {
enhancedConfiguration.setBeanFactory(this.beanFactory);
}
return pvs;
}

注释点明了时序敏感性:必须赶在 AutowiredAnnotationBeanPostProcessor 之前注⼊。因为⼀旦开始⾃动装配这个配置类的其他字段,那些字段的解析过程就可能触发别的@Bean ⽅法调⽤——那时候 $$beanFactory 要是还是 null,整个机制就断了。

7.2 分⽔岭:⼀个 ThreadLocal好,配置类的增强⼦类⼿⾥有 BeanFactory 了。现在看它怎么区分"是谁在调我"。

// [framework] .../annotation/ConfigurationClassEnhancer.java:350-401(省略 FactoryBean与 scoped proxy分⽀)

public @Nullable Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
MethodProxy cglibMethodProxy) throws Throwable {
ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance); // :354读 $$beanFactory
String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod, beanFactory);

// ...(:358-382:scoped proxy与 FactoryBean的特殊处理)

if (isCurrentlyInvokedFactoryMethod(beanMethod)) { // :384 ←分⽔岭

// The factory is calling the bean method in order to instantiate and register the bean

// (i.e. via a getBean() call) -> invoke the super implementation of the method to actually

// create the bean instance.

return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs); // :398真造
}
return resolveBeanReference(beanMethod, beanMethodArgs, beanFactory, beanName); // :401⾛容器
}

整个机制的重量,全压在 :384 这⼀个 if 上。⽽这个 if 的实现是:

// :510-514

private boolean isCurrentlyInvokedFactoryMethod(Method method) {
Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod();
return (currentlyInvoked != null && method.getName().equals(currentlyInvoked.getName()) &&
Arrays.equals(method.getParameterTypes(), currentlyInvoked.getParameterTypes()));
}

顺着 getCurrentlyInvokedFactoryMethod 摸到另⼀个仓的另⼀个包:

// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java:47-82

private static final ThreadLocal<Method> currentlyInvokedFactoryMethod = new ThreadLocal<>();
public static @Nullable Method getCurrentlyInvokedFactoryMethod() {
return currentlyInvokedFactoryMethod.get();
}

/** @since 6.2 */

public static <T> T instantiateWithFactoryMethod(Method method, Supplier<T> instanceSupplier) {
Method priorInvokedFactoryMethod = currentlyInvokedFactoryMethod.get();
try {
currentlyInvokedFactoryMethod.set(method);
return instanceSupplier.get();
}
finally {
if (priorInvokedFactoryMethod != null) {
currentlyInvokedFactoryMethod.set(priorInvokedFactoryMethod); //恢复上⼀层,⽀持嵌套
}
else {
currentlyInvokedFactoryMethod.remove();
}
}
}

⽽作坊真正通过⼯⼚⽅法造器的地⽅( :148-152 ),正是包在这个⽅法⾥的。

于是整件事可以⼀句话说完:

"到底是容器在调我,还是⽤户在调我?"——答案存在⼀个 ThreadLocal ⾥。

容器要通过⼯⼚⽅法造⼀件器时,会先把当前这个⼯⼚⽅法记进 SimpleInstantiationStrategy 的 ThreadLocal。CGLIB 拦截器⼀⽐对:名字和参数类型都对上 → 是容器在调 → invokeSuper 真正执⾏你写的⽅法体,new ⼀个新对象出来;对不上(或者是 null)→ 是⽤户或者别的 @Bean ⽅法在调 → 转成beanFactory.getBean(beanName) ,把容器⾥那个单例递出去。

回到开场: a() 被容器调⽤时,ThreadLocal ⾥记的是 a ; a() 内部调 b() 时,ThreadLocal ⾥记的还是 a ——名字对不上,于是 b() ⾛ getBean("b") 。⽽容器⾃⼰造 b 时,ThreadLocal ⾥记的是 b ,名字对上了,才真的 new B() 。

⼀次真正的构造,⽆数次转发。

🦴 ⼀个细到⻣头⾥的细节:⽐对时只⽐⽅法名和参数类型,不⽐返回类型。注释 :504-508 给了理由:

Compares method name and parameter types only in order to work around a potential problem with covariant return types (currently only known to happen on
Groovy classes).

为了 Groovy 的协变返回类型,牺牲了⼀点点精确性。这种"为某个具体语⾔的具体⾏为留后⻔"的注释,在 Spring ⾥随处可⻅——它是⼀个跑了⼆⼗多年的框架该有的样⼦。

7.3 ✨ 这是全书唯⼀⼀层"反着装"的壳现在请把这⼀章和 AOP 那条线放在⼀起看。

AOP 的壳( @Transactional 、 @Cacheable ):拦的是从外⾯进来的调⽤。你在类⾥⾯ this.method() ,⾛的是原件⾃⼰的⽅法表,壳拦不住——于是事务静默失效。这是 Spring ⽣态被骂了⼗⼏年的头号坑。

配置类的壳:容器从外⾯调 @Bean ⽅法时,它放⾏( invokeSuper );恰恰是你在类⾥⾯调 b() 的时候,它才拦。

同⼀个 CGLIB,同⼀个"套壳"⼿法,两套完全相反的语义。

AOP 的壳希望"外⾯进来的调⽤被加⼯,⾥⾯的⾃调⽤不管";配置类的壳希望"⾥⾯的⾃调⽤被改写成容器查询,外⾯进来的调⽤照常执⾏"。⽽配置类之所以能做到 AOP 做不到的事,靠的不是别的⼿段,就是那个 ThreadLocal——它给了拦截器⼀个 AOP 代理永远没有的信息:调⽤是从容器的哪⼀层来的。

AOP 代理没有这个信息,因为它⾯对的是任意业务⽅法,容器不可能为每个业务⽅法维护⼀个"我正在调它"的标记。配置类能作弊,是因为它的调⽤⼊⼝有且只有⼀个:⼯⼚⽅法。

这是"壳"这个隐喻在本书⾥第⼀次被反过来⽤。记住这个反差——等后⾯讲到 AOP 与 @Transactional ⾃调⽤失效时,它会让你对"为什么⾃调⽤救不了"有完全不同的理解:

那不是 Spring 偷懒,是它在配置类这个受控场景⾥已经证明了,要拦住⾃调⽤需要多苛刻的前提(调⽤⼊⼝唯⼀、且容器愿意为这个⼊⼝维护⼀个 ThreadLocal 标记)。业务⽅法两个条件⼀个都不满⾜。

⼋、代价与边界:壳不是⽩套的enhance() 的边界处理⾥,藏着这层壳的全部账单。

其⼀,失败时的异常信息就是最好的⽂档( :135-139 ):

catch (CodeGenerationException ex) {
throw new BeanDefinitionStoreException("Could not enhance configuration class [" + configClass.getName() +
"]. Consider declaring @Configuration(proxyBeanMethods=false) without inter-bean references " +
"between @Bean methods on the configuration class, avoiding the need for CGLIB enhancement.", ex);
}

其⼆, @Configuration 类不能 final——但条件⽐你想的严格。

// [framework] .../annotation/ConfigurationClass.java:248-252

// A configuration class may not be final (CGLIB limitation) unless it does not have to proxy bean methods
if (attributes != null && (Boolean) attributes.get("proxyBeanMethods") && hasNonStaticBeanMethods() &&
this.metadata.isFinal()) {
problemReporter.error(new FinalConfigurationProblem());
}
三个条件是「与」的关系: proxyBeanMethods=true 且 有⾮ static @Bean ⽅法 且 类是 final,才报错。所以 @Configuration(proxyBeanMethods = false) 的 final 配

置类,完全合法。

@Bean ⽅法这边的约束同样精确( [framework] .../annotation/BeanMethod.java:49-71 ): @Bean 上挂 @Autowired 报错;返回 void 报错;static ⽅法到此为

⽌,"no further constraints"( :61-64 );⾮ static 且 proxyBeanMethods=true 且⽅法不可覆写(private/final)→ 报错。

⽽报告这些问题的默认实现是 FailFastProblemReporter ( ConfigurationClassPostProcessor.java:176 )——默认 fail-fast,启动就炸。

其三, static @Bean 是逃⽣舱,机械原理在这三⾏:

// [framework] .../annotation/ConfigurationClassBeanDefinitionReader.java:239-253

if (metadata.isStatic()) {

// static @Bean method

beanDef.setBeanClass(...); //配置类本身当 beanClass
beanDef.setUniqueFactoryMethodName(methodName); // →静态⼯⼚⽅法
}
else {

// instance @Bean method

beanDef.setFactoryBeanName(configClass.getBeanName()); // →实例⼯⼚⽅法,依赖配置类这件器
beanDef.setUniqueFactoryMethodName(methodName);
}

static @Bean 不需要配置类实例,所以不触发配置类的提前实例化,也不受 CGLIB 增强。这就是那条流传已久的规矩——"产出 BFPP/BPP 的 @Bean ⽅法必须写 static"——背后的全部机械原理。死结是这样的:BFPP 必须在配置类被完整装配之前就造出来,⽽实例 @Bean ⽅法必然要求先有配置类实例。static ⼯⼚⽅法不需要实例,⼀⼑解开。

其四,⚠ 增强被跳过时,只有⼀条 WARN。

// [framework] ConfigurationClassPostProcessor.java:549-557

else if (beanFactory.containsSingleton(beanName)) {
if (logger.isWarnEnabled()) {
logger.warn("Cannot enhance @Configuration bean definition '" + beanName +

"' since its singleton instance has been created too early. The typical cause " +"is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +"return type: Consider declaring such methods as 'static' and/or marking the " +

"containing configuration class as 'proxyBeanMethods=false'.");
}
}

这是本章最该被批评的⼀处。这条⽇志的诊断质量堪称⼀流——它直接点名了最常⻅的病因和两个修法。但它只是⼀条 WARN。

后果是什么?你的 @Configuration 类没有被增强, @Bean ⽅法互调退化成普通 Java 调⽤,本该是单例的东⻄被 new 出了好⼏份。这是⼀个静默的语义降级,运⾏时不报错,只在你某天发现"为什么两个地⽅注⼊的 DataSource 不是同⼀个"时才浮出⽔⾯。

⽽同⼀个类⾥, Configuration 类 final 是 fail-fast, @Bean 返回 void 是 fail-fast, @ComponentScan 撞上 REGISTER_BEAN 条件是直接抛异常——偏偏这个后果最严重、最难排查的情况,是 WARN。我理解取舍:抛异常会让⼀批历史应⽤启动不了。但⼀个默认 fail-fast 的⼦系统,在最危险的那⼀格上选了放⾏,这个不⼀致本身就值得被指出来。

其五,能⼒的硬边界:final 的 FactoryBean。

若⼀个 @Bean ⽅法返回 FactoryBean 且在配置类内部被调⽤,Spring 会给这个 FactoryBean 再包⼀层代理,把 getObject() 也转成 getBean(beanName) (对⻬ XML的语义, :516-521 )。但:

// :530-548

if (finalClass || finalMethod) {
if (exposedType.isInterface()) {
return createInterfaceProxyForFactoryBean(...); //返回类型是接⼝ → JDK动态代理救场
}
else {
logger.debug("Unable to proxy FactoryBean '" + beanName + "' ... because its " +
(finalClass ? "implementation class" : "getObject() method") + " is final: " +
"A getObject() call will NOT be routed to the factory. " +
"Consider declaring the return type as a FactoryBean interface.");
return factoryBean; //放弃
}
}

final 的实现类 + ⾮接⼝的返回类型 = 放弃,只留⼀条 debug ⽇志。这是"照原件仿造⼀个⼦件"这种⼿法与⽣俱来的边界: final 的地⽅,仿不了。

其六,⽣成类叫什么名字。

// [framework] spring-core/src/main/java/org/springframework/cglib/core/SpringNamingPolicy.java:35

private static final String SPRING_LABEL = "$$SpringCGLIB$$";

所以调试器⾥那个 com.example.Cfg$$SpringCGLIB$$0 ,就是你的配置类被套上的那层壳。看到它,说明这个类是 full 模式并且增强成功了;没看到它,就说明它是 lite、或者被降级了、或者增强被那条 WARN 跳过了。这是最快的⼀次性诊断。

九、Boot 是怎么把这套机制⽤满的Framework 提供机制,Boot 把它⽤到了极限。三条最值得记的:

其⼀,整个⾃动配置就是⼀个 DeferredImportSelector 。

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java:78public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ...// :81

static final int ORDER = Ordered.LOWEST_PRECEDENCE - 1;

它排在所有 DeferredImportSelector 的倒数第⼆——⽤户⾃⼰的选择器先⾛。⽽"deferred"意味着它在 ConfigurationClassParser.parse(Set) 的最后⼀⾏才被处理( [framework] ConfigurationClassParser.java:200 ),也就是所有普通配置类都解析完之后。这个时机是刻意的:⾃动配置类身上挂满了@ConditionalOnMissingBean ,得等⽤户的定义全都在册了,条件判定才有意义。

其⼆,所有⾃动配置类都是 lite。

// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfiguration.java:37-38, 58

* {@link Configuration @Configuration} with the exception that
* {@link Configuration#proxyBeanMethods() proxyBeanMethods} is always {@code false}.

...

@Configuration(proxyBeanMethods = false)
public @interface AutoConfiguration {

⼏百个⾃动配置类,⼀个 CGLIB ⼦类都不⽣成。这对启动时间是实打实的收益。代价是这些类⾥的 @Bean ⽅法不能互相调⽤,只能靠⽅法参数注⼊——你翻开 [boot]module/spring-boot-*/ 下任意⼀个 *AutoConfiguration.java ,看到的都是这个⻛格。这不是编码偏好,是 lite 模式逼出来的纪律。

(对照⼀下: [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringBootConfiguration.java 的 proxyBeanMethods() 默认仍是 true ——

⽤户⾃⼰的配置类默认还是 full,只不过要过第 6.1 节那道降级关。)

其三,"只改图纸不碰实例"的教科书范例。

// [boot] core/spring-boot/src/main/java/org/springframework/boot/LazyInitializationBeanFactoryPostProcessor.java:54, 111-112

public final class LazyInitializationBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {
public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; }

spring.main.lazy-initialization=true 的全部实现,就是遍历所有 bean definition 把 lazyInit 打开。⼀个配置项,⼀个 BFPP,零实例接触。这才是BeanFactoryPostProcessor 被设计出来的样⼦。

🎯 三句带⾛1. BDRPP 能加/删图纸,BFPP 只能改图纸上的字;所有 BDRPP 的 postProcessBeanDefinitionRegistry 必须全部跑完,才允许任何⼀个postProcessBeanFactory 开始。编程式注册的 post-processor ⼀律按注册顺序执⾏, PriorityOrdered / Ordered / @Order 全部被忽略。

2. @Configuration 默认 proxyBeanMethods=true → full 模式 → CGLIB ⼦类。但本基线(Framework 7.1.0-SNAPSHOT)会把"没有实例级 @Bean ⽅法"的 full 类降

级为 lite,不⽣成⼦类。 @Component + @Bean 是 lite,⽅法互调不⾛容器。

  1. @Bean ⽅法互调返回同⼀单例,靠的是 SimpleInstantiationStrategy ⾥的⼀个 ThreadLocal<Method> 。拦截器⽐对"当前正在被容器调⽤的⼯⼚⽅法"是否就是⾃⼰:是 → 真执⾏;否 → 转成 getBean(beanName) 。

承上启下图纸画完了,也盖了章。full 模式的配置类,它的 BeanDefinition ⾥ beanClass 已经被悄悄换成了那个名字⾥带 $$SpringCGLIB$$ 的⼦类;每个 @Bean ⽅法,也都变成了⼀张写着"⼯⼚⽅法:某某类的某某⽅法"的图纸。

refresh() 的第 604 ⾏到此结束。第 622 ⾏, finishBeanFactoryInitialization 要开始了——作坊终于要动⼿照图施⼯。

可施⼯这件事,⽐"照图造出来"复杂得多。⼀次 getBean("orderService") 到底发⽣了什么?为什么要先去三个缓存⾥各摸⼀遍?为什么会有"这件器正在造,别急"的标记?

为什么明明是单例,代码⾥还要套⼀层 synchronized ?为什么造出来的东⻄,最后递到你⼿上时可能已经不是它了?

下⼀章,我们跟着⼀次 getBean ⾛完全程。

从那句 Object sharedInstance = getSingleton(beanName); 开始。