源码小说CodeStory
登录
上一章

40,591 字 · 约 101 分钟

下一章
字体

主题

版式

第16章 卷五 · 总装房 · 开工十二道:refresh()

卷五 · 总装房

开⼯⼗⼆道:refresh()

「我⼏乎什么都不⼲。我只是决定谁先⼲、谁后⼲。 ——但整座坊之所以能开⼯,正因为有⼈把这个顺序钉死了。」 —— AbstractApplicationContext.refresh() 的⾃⽩⼀、⼋⼗⼀⾏的⽬录⻚我第⼀次翻开这⼀⻚时,是失望的。

AbstractApplicationContext 整整 1673 ⾏( wc -l 实测),⽽全书传说中的核⼼ refresh() ,只有 81 ⾏—— [framework] spring-

context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:582-662 。⽽且这 81 ⾏⾥,真正"⼲活"的⼀⾏也没有。它全在派活:

// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:582@Override

public void refresh() throws BeansException, IllegalStateException {
this.startupShutdownLock.lock();
try {
this.startupShutdownThread = Thread.currentThread();
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

// Prepare this context for refreshing.

prepareRefresh(); // :590⼯序 1

// Tell the subclass to refresh the internal bean factory.

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // :593⼯序 2

// Prepare the bean factory for use in this context.

prepareBeanFactory(beanFactory); // :596⼯序 3

try { // :598 ←保护区从这⾥才开始

postProcessBeanFactory(beanFactory); // :600⼯序 4
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
invokeBeanFactoryPostProcessors(beanFactory); // :604⼯序 5
registerBeanPostProcessors(beanFactory); // :606⼯序 6
beanPostProcess.end();
initMessageSource(); // :610⼯序 7
initApplicationEventMulticaster(); // :613⼯序 8
onRefresh(); // :616⼯序 9
registerListeners(); // :619⼯序 10
finishBeanFactoryInitialization(beanFactory); // :622⼯序 11
finishRefresh(); // :625⼯序 12
}
catch (RuntimeException | Error ex) { // :628

...

}
finally {
contextRefresh.end(); // :655
}
}
finally {
this.startupShutdownThread = null;
this.startupShutdownLock.unlock();
}
}

(注释是我为对⻬⼯序号补的,⽅法调⽤与⾏号⼀字未动。)

失望只持续了三分钟,然后我意识到:这就是它的价值。

这 81 ⾏不是实现,是⽬录⻚。是⼀张贴在总装房墙上的⼯序卡。整座成器坊⾥最重的⼀件事——把⼀堆死的图纸( BeanDefinition )变成⼀屋⼦活的、互相扣好榫卯的器——被拆成了⼗⼆道,⽽这⼀⻚做的唯⼀⼀件事,是把这⼗⼆道的先后次序钉死。

顺便澄清⼀件事:全书意象表⾥写" refresh() = 开⼯的⼗⼆道⼯序",我原以为"⼗⼆"是为了顺⼝凑的修辞。数完源码才发现——真的就是⼗⼆个⽅法调⽤,⼀个不多,⼀个不少。这次修辞刚好对上了账。

⽽这⼀⻚最值得看的,恰恰不是那⼗⼆⾏,是第 598 ⾏那个 try 的位置。

它开在⼯序 3 之后。也就是说:⼯序 1、2、3 不在保护区⾥。

先记住这根刺。我们⾛完全程再回来拔它。

⼆、⼯序 1 · prepareRefresh() —— 先宣布活着,再开始⼲活// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:668

protected void prepareRefresh() {

// Switch to active.

this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);

...

initPropertySources(); // :684
getEnvironment().validateRequiredProperties(); // :688

// Store pre-refresh ApplicationListeners...

if (this.earlyApplicationListeners == null) { ... } // :691
else { this.applicationListeners.clear(); ... }

// Allow for the collection of early ApplicationEvents,// to be published once the multicaster is available...

this.earlyApplicationEvents = new LinkedHashSet<>(); // :702
}

做了什么。 四件事:打时间戳、翻活标记、跑两个环境相关的钩⼦、给"还没有⼴播器"的那段真空期准备⼀个事件缓冲区。

为什么这么设计。 三处值得停下来。

第⼀, active.set(true) 在最前⾯。这不是笔误,是必需:后⾯⼗⼀道⼯序⾥的很多调⽤会经过 assertBeanFactoryActive() ( :1281 ),要是这会⼉还没置活,⾃⼰就把⾃⼰卡死了。代价是它撒了⼀个可能永远不被纠正的谎——待会⼉讲失败路径时兑现。

第⼆, getEnvironment().validateRequiredProperties() ( :688 )。这是整个启动流程⾥, setRequiredProperties 声明的那些"必填属性"唯⼀⼀次被校验的机会。第 688

⾏放过去了,后⾯再没有第⼆个⼈管这事。很多⼈以为"必填校验"是个贯穿始终的守卫,不是——它是⼀道⼀次性的⻔。

第三,也是最⻅功⼒的⼀处: earlyApplicationEvents 这个缓冲区( :702 )。

它为什么必须在这⾥建?因为⼴播器要到⼯序 8 才存在。从⼯序 2 到⼯序 7,中间任何⼈调 publishEvent ——⽐如⼀个 BeanFactoryPostProcessor 想吼⼀嗓⼦——都不能把事件丢了。于是 publishEvent 内部⻓这样:

// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:444// Multicast right now if possible - or lazily once the multicaster is initialized

if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.multicastEvent(applicationEvent, eventType);
}

⚠ 暗礁在这⾥,⽽且是⼀条被业界集体传错的暗礁。

这两个分⽀都不命中时会怎样?——什么也不会发⽣。事件被静默丢弃,不抛异常、不打⽇志。

哪两种情况会落进这个空档?⼀是 refresh 从未开始(缓冲区还是 null、⼴播器也是 null);⼆是 context 已经 close( doClose() 在 :1226 把 applicationEventMulticaster置回了 null)。

⽽⽹上⼴为流传的那句"refresh 之前 publishEvent 会抛 ApplicationEventMulticaster not initialized "——那句报错确实存在,在

getApplicationEventMulticaster() ⾥( :468-474 )——但 publishEvent 根本不⾛那个⽅法。它只在 registerListeners() 和 ApplicationListenerDetector ⾥

被调⽤。所以在本基线上,"refresh 前 publishEvent 会报错"这个说法不成⽴。你得到的是沉默。

Boot 侧有⼀句注释可以侧⾯印证 Spring ⾃⼰也知道这个空档: [boot] core/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java:123-124 写着 "An inactive context may not have a multicasterso we use our multicaster to call all the context's listeners instead"——它宁可⾃带⼀个 multicaster,也不敢把早期事件交给 context 发。

三、⼯序 2 · obtainFreshBeanFactory() —— 向⼦类要⼀个"新鲜的"作坊// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:720

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}

两⾏。真正的分岔在那两个抽象⽅法上( :1633 与 :1656 ),⽽两条实现路线的差别,是理解"为什么有的 context 能重复 refresh、有的不能"的全部答案。

路线 A: GenericApplicationContext ( AnnotationConfigApplicationContext 和 Boot 全家都在这条线上)

// [framework] spring-context/src/main/java/org/springframework/context/support/GenericApplicationContext.java:296

protected final void refreshBeanFactory() throws IllegalStateException {
if (!this.refreshed.compareAndSet(false, true)) {
throw new IllegalStateException(
"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
}
this.beanFactory.setSerializationId(getId());
}

作坊是构造期就 new 好的 final 字段,这⾥根本不"刷新"什么,只放了⼀道⼀次性闸⻔。

路线 B: AbstractRefreshableApplicationContext ( ClassPathXmlApplicationContext 那⼀⽀)

// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableApplicationContext.java:119

protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
beanFactory.setApplicationStartup(getApplicationStartup());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
this.beanFactory = beanFactory;
}
catch (IOException ex) { ... }
}

这条是真的推倒重来:拆掉旧作坊、重建、重新读⼀遍图纸。代价是整个 BeanFactory 全部重建,收益是⽀持反复 refresh。

✨ 顺带解⼀个⽼问题。 那个 refreshed 是 AtomicBoolean ,⽽且——注意——失败之后不会复位。 GenericApplicationContext 的 cancelRefresh 覆写( :305-308 )只

把 serializationId 置了 null,压根没碰 refreshed :

// [framework] spring-context/src/main/java/org/springframework/context/support/GenericApplicationContext.java:305@Override

protected void cancelRefresh(Throwable ex) {
this.beanFactory.setSerializationId(null);
super.cancelRefresh(ex);
}

结论很硬:⼀个 Boot 应⽤的 context ⼀旦 refresh 失败,就永久报废了,连"重试⼀次"都不允许,只能新建。 这不是缺陷——⼀个刷了⼀半的对象图,你也确实不该在原地缝合它——但它意味着"启动失败⾃动重试"这种运维想象,在 Spring 这⾥从架构上就不成⽴。

关于循环依赖的默认值,顺⼿在这⾥坐实⼀下(这是最容易被写错的⼀处):

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

private boolean allowCircularReferences = true;

Framework 裸⽤时,循环依赖是允许的。 ⽽ Boot 4 把它反了过来,证据在第九节。同⼀个开关、两个仓两种默认——这是全书必须讲清的⼀处对照,也是"我明明记得 Spring ⽀持循环依赖啊"这类困惑的根源。

四、⼯序 3 · prepareBeanFactory() —— "作坊"与"总装房"差在哪的物证清单如果有⼈问你: BeanFactory 和 ApplicationContext 到底差在哪?别背书上那句"后者功能更多"。带他看这⼀段( :730-776 )。这 47 ⾏就是全部差价的物证清单。

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

beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);

// BeanFactory interface not registered as resolvable type in a plain factory.

// MessageSource registered (and found for autowiring) as a bean.
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); // :748
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

// Register early post-processor for detecting inner beans as ApplicationListeners.

beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // :754

做了什么。 给⼀间只会照图造器的裸作坊,装上⼀整套"总装房外挂":

  1. Aware 回调的执⾏者( :737 )。 ApplicationContextAwareProcessor 是个包级私有类,⽤户引⽤不到。它的实现就是⼀串写死顺序的 if instanceof ( [framework]
.../ApplicationContextAwareProcessor.java:90-112 ):Environment → EmbeddedValueResolver → ResourceLoader → ApplicationEventPublisher →

MessageSource → ApplicationStartup → ApplicationContext。所谓"Aware 机制",拆开看就是这七个 if。

  1. ignoreDependencyInterface 七连( :738-744 )。语义是:"这七个接⼝的 setter 由上⾯那个 Aware 处理器负责填,byType ⾃动装配请绕⾏。"没有这七⾏,⼀个ApplicationContextAware 的 setter 会被⾃动装配和 Aware 机制抢着填两次。
3. registerResolvableDependency 四连( :748-751 )。这四⾏回答了⼀个⼏乎⼈⼈踩过的悬案:为什么 @Autowired ApplicationContext ctx 能注⼊,但
getBeanNamesForType(ApplicationContext.class) ⼀个都找不到?

因为它根本不是 bean。它是登记在"可解析依赖"表⾥的⼀个类型→实例映射,只在装配时被查,不在图纸库⾥挂号。旁边那⾏注释还特意补了⼀句: MessageSource registered

(and found for autowiring) as a bean. ——MessageSource ⾛的是 bean 这条路(⼯序 7 会 registerSingleton ),所以它反⽽能被 getBean 找到。同⼀个类⾥,两种截

然不同的可⻅性策略,靠⼀⾏注释区分。

🦴 ⻣灰级细节:⼀处⼏乎没⼈注意的不对称。

看第 757 ⾏和第 764 ⾏,同⼀段代码⾥⽤了两个不同的判断⽅法:

// [framework] .../AbstractApplicationContext.java:757

if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { ... }

// ...// [framework] .../AbstractApplicationContext.java:764

if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
containsBean 会穿透到⽗容器, containsLocalBean 不会。⽽这个选择在全类⾥是⼀以贯之的:LTW( :757 )、bootstrapExecutor( :948 )、conversionService( :955 )⽤
containsBean ;environment 四件套( :764-775 )、messageSource( :823 )、multicaster( :856 )、lifecycleProcessor( :882 )⽤ containsLocalBean 。

翻译成⼈话:⼦容器会"继承"⽗容器的类型转换服务和引导线程池,但绝不会继承⽗容器的 environment、messageSource、⼴播器。 前者是⽆状态的⼯具,共⽤⽆害;后者是有身份的基础设施,每个容器必须有⾃⼰的⼀份。这个区分做得⾮常克制,但它从来没被写进任何⽂档,只写在了⽅法名的选择⾥。

五、⼯序 4 与⼯序 9 —— 模板⽅法的两个逃⽣舱这两道放在⼀起讲,因为它们在 AbstractApplicationContext ⾥都是空的:

// [framework] .../AbstractApplicationContext.java:787

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

// [framework] .../AbstractApplicationContext.java:907

protected void onRefresh() throws BeansException {

// For subclasses: do nothing by default.

}

两个空⽅法,却是整条流⽔线上最贵的两块地⽪。因为它们的位置选得极准:

⼯序 4 卡在"图纸已加载、但⼀个 post-processor 都还没跑、⼀个器都还没造"这个瞬间。它的 javadoc 把这个契约写死了( :778-786 ):"The initial definition resourceswill have been loaded but no post-processors will have run and no derived bean definitions will have been registered, and most importantly, no beans will havebeen instantiated yet."

⼯序 9 卡在"所有 post-processor 都就位、基础设施 bean 都建好、但批量造器还没开始"这个瞬间。

Boot 两块地⽪都占了,⽽且⽤得很漂亮。⼯序 4 这块:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/context/ServletWebServerApplicationContext.java:134

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
registerWebApplicationScopes();
}

形状和⼯序 3 ⼀模⼀样:加⼀个 Aware 处理器 + ignore ⼀个接⼝ + 注册 scope,只是把"上下⽂那套"换成了"Servlet 那套"。Framework 定的模式,Boot 照着填了⼀份。

(顺带⼀记纪律提醒:这个类在 Boot 4 ⾥的家是 org.springframework.boot.web.server.servlet.context ,属于 module/spring-boot-web-server 模块。Boot 3 时代⼤

家背熟的 org.springframework.boot.web.servlet.context 在本基线上已经不是它的地址——Boot 4 做过⼀次明显的⽬录重组,照抄旧包名会错。)

⼯序 9 那块地⽪更重,留到第⼋节讲——Boot 的整个 Tomcat 就诞⽣在那⼀格⾥。

六、⼯序 5 与⼯序 6 —— 全书主线:先改图纸,再排过⼿的⼈这两道是⼗⼆道⾥的脊梁。整本书那句"先改图纸,再注册过⼿的⼈,最后才造器",物理位置就在第 604 和第 606 ⾏,中间隔着⼀个空⾏。

⼯序 5:改图纸的⼈先动⼿// [framework] .../AbstractApplicationContext.java:795

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

// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime

// (for example, through a @Bean method registered by ConfigurationClassPostProcessor)
if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null &&
beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}

正事⼀⾏就委托出去了(BFPP 与配置类解析的细节不归本章)。但它后⾯那段"补漏"值得单独看。

⼯序 3 已经探测过⼀次 loadTimeWeaver 了( :757 ),这⾥为什么⼜探测⼀遍?注释写得明明⽩⽩:"for example, through a @Bean method registered by

ConfigurationClassPostProcessor"。

因为⼯序 5 才是 @Configuration 类被解析、 @Bean 定义被注册的时刻。⼯序 3 那会⼉去问"有没有 loadTimeWeaver 这个 bean",答案很可能是没有——它还躺在⼀个没被解析的配置类⾥。这是⼀处"同⼀件事必须做两遍"的活化⽯,它把流⽔线的顺序约束暴露得淋漓尽致:任何依赖"图纸库已完整"的判断,都不能早于⼯序 5。

⼯序 6:把过⼿的⼈排好队registerBeanPostProcessors() 本体只有⼀⾏,活全在 delegate ⾥。⽽这个 delegate ⽅法的开头,顶着⼀段全 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. ...//

// 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 之前,先去把那⼀⻓串被拒的 PR 看完。"——他们甚⾄把查询链接直接写进了源码。这不是注释,这是⼀块墓碑。

排队规则是四趟扫描 + 两条尾巴( :227-291 ):先只拿名字不实例化;塞⼀个 BeanPostProcessorChecker 进去当哨兵( :232-234 );按 PriorityOrdered / Ordered / 普通分成三拨,⼀拨全部注册完再动下⼀拨;然后是两条关键的尾巴。

尾巴⼀( :285-287 ):所有 MergedBeanDefinitionPostProcessor 被重新排序、重新注册到队尾。 AutowiredAnnotationBeanPostProcessor 、

CommonAnnotationBeanPostProcessor 就是靠这⼀步被挪到后⾯去的。

尾巴⼆( :289-291 ),这是我最喜欢的⼀处⼩动作:

// [framework] .../PostProcessorRegistrationDelegate.java:289// Re-register post-processor for detecting inner beans as ApplicationListeners,

// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
ApplicationListenerDetector 在整个 refresh ⾥被 new 了两次——⼯序 3 ⼀次( :754 ),这⾥⼀次。为什么?注释说得含蓄: for picking up proxies etc 。

展开说就是:这个探测器的活⼉是在 postProcessAfterInitialization ⾥把"实现了 ApplicationListener 的器"捞出来注册进⼴播器。如果它排在队列前⾯,它捞到的是还没套壳的原件;⽽ AOP 的⾃动代理创建器也是个 BeanPostProcessor ,排在它后⾯——于是注册进⼴播器的是原件,真正被别⼈使唤的却是壳。两个对象,事件发给了错的那个。

把它挪到队尾,捞到的就是最终那件套好壳的器。它靠 equals() 按 context 身份判等( [framework] .../ApplicationListenerDetector.java:118-122 ),所以第⼆次 add

会把⼯序 3 那次去重掉,效果就是"移到末尾"。

⼀个 new ,把"AOP 代理什么时候产⽣"和"监听器注册的到底是谁"两个问题串成了⼀根线。

⚠ ⽽那个哨兵 BeanPostProcessorChecker ,是你调试⽣涯的⽼朋友。 那条著名的警告:

... is not eligible for getting processed by all BeanPostProcessors

(for example: not eligible for auto-proxying)

出处就在 [framework] .../PostProcessorRegistrationDelegate.java:430 和 :438 两个分⽀。它的意思是:有件器在"过⼿的⼈"还没排完队的时候就被造出来了,它漏掉了队伍后半段的所有⼯序——包括⾃动代理。

这就是"我的 @Transactional 为什么没⽣效"的第⼀现场,⽽且往往和另⼀个原因(同类⾃调⽤, this.method() 喊不到壳上)⻓得很像、症状完全⼀致。区别是:这条⾄少还给你留了⼀⾏ warn ⽇志,⾃调⽤失效则是彻底的沉默。

哨兵还⾜够体贴,能识别⼀种典型错误并直接给⽅案( :427-435 ):你的 BPP 是被⼀个⾮ static 的 @Bean ⼯⼚⽅法声明的,于是造它得先造那个配置类,连累⼀串 bean 提前出⽣—— consider declaring it as static instead 。 ROLE_INFRASTRUCTURE 的 bean 被豁免( :451 ),因为框架⾃⼰那些内部件本来就不需要过全套⼯序。

七、⼯序 7 与⼯序 8 —— ⼀次写进 javadoc 的单向依赖裁决

initMessageSource() ( :821-846 )和 initApplicationEventMulticaster() ( :854-871 )是同⼀个模⼦刻的:本地有就⽤你的,没有就 new ⼀个默认的,然后

registerSingleton 塞进去。

// [framework] .../AbstractApplicationContext.java:838

DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);

⚠ registerSingleton 这个词要划重点。 它是"把⼀个已经造好的现成对象直接塞进单例池",不⾛ BeanDefinition、不经过任何 BeanPostProcessor。后果是:这些默认的

messageSource、multicaster,以及⼯序 12 的 lifecycleProcessor、Boot 的 webServerStartStop 和 springApplicationArguments ——统统不会被 AOP 代理,统统享受不到任何 BPP 的加⼯。

它们在图纸库⾥没有图纸。它们不是"照图造出来的器",是"从外⾯搬进来直接摆上货架的器"。你能 getBean 到它们,但你永远拦不住它们的⽅法调⽤。这是⼀条极⼲净的规律,也是很多"我给它加了切⾯怎么不⽣效"的谜底。

那为什么 MessageSource 必须排在⼴播器前⾯?

这⼀次不⽤猜。Spring 把答案写在 javadoc ⾥,⽽且写了两遍( :374 和 :387 , publishEvent 的两个重载各⼀份):

Note: Listeners get initialized after the MessageSource, to be able to access it within listener implementations. Thus, MessageSource implementations cannotpublish events.**这是⼀次公开的、有署名的单向依赖裁决:两边不可能都赢,于是他们选了"监听器⾥能⽤ MessageSource",代价是"MessageSource ⾥不能发事件"。没有绕、没有懒加载魔法、没有双向解耦——就是排个顺序,然后把代价⽼实写在⽂档⾥。

顺⼿把最容易被写错的默认值坐实。 事件到底是同步还是异步?

// [framework] spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java:54

private @Nullable Executor taskExecutor;
private @Nullable ErrorHandler errorHandler;

// [framework] .../SimpleApplicationEventMulticaster.java:137

public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : ResolvableType.forInstance(event));
Executor executor = getTaskExecutor();
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null && listener.supportsAsyncExecution()) {
try { executor.execute(() -> invokeListener(listener, event)); }
catch (RejectedExecutionException ex) {
// Probably on shutdown -> invoke listener locally instead
invokeListener(listener, event);
}
}
else { invokeListener(listener, event); }
}
}

两个字段初值都是 null。结论:

Spring 事件默认完全同步,在发布者的线程⾥,⼀个接⼀个串⾏执⾏。"发个事件解耦⼀下"不等于"扔到后台去了"——它就在你的调⽤栈⾥,⽽且是你的事务⾥。

即使配了 executor,监听器还得 supportsAsyncExecution() 返回 true 才真异步;线程池拒绝时会悄悄回落到本地同步执⾏( :144-146 )。

errorHandler 也是 null,意味着任何⼀个监听器抛异常,整条事件链当场断掉,异常直接冒泡给发布者。第三个监听器炸了,第四第五个就永远收不到这个事件。

⼋、⼯序 9 · onRefresh() —— Tomcat 诞⽣在这⼀格前⾯说⼯序 9 是块贵地⽪。贵在哪?Boot 的整个内嵌 Web 容器就是在这⼀格⾥被造出来的。

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/context/ServletWebServerApplicationContext.java:161

protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
createWebServer() ( :183 )拿到 ServletWebServerFactory 、造出 WebServer ,然后⼲了件耐⼈寻味的事:

// [boot] .../ServletWebServerApplicationContext.java:193

getBeanFactory().registerSingleton("webServerGracefulShutdown",
new WebServerGracefulShutdownLifecycle(webServer));
getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, webServer));

它没有在这⾥启动 Tomcat。 它只是把两个 SmartLifecycle 注册了进去。

这是本基线与"Boot 2 时代常识"最⼤的⼀处分歧,务必更新记忆。 ⽼⽂章都说"Boot 在 finishRefresh() ⾥ webServer.start() 并发

ServletWebServerInitializedEvent "。我 grep 过了: ServletWebServerApplicationContext 在 Boot 4 ⾥根本没有覆写 finishRefresh() 。 那套逻辑已经整个搬到了

Lifecycle 机制上:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/context/WebServerStartStopLifecycle.java:42@Override

public void start() {
this.webServer.start();
this.running = true;

this.applicationContext

.publishEvent(new ServletWebServerInitializedEvent(this.webServer, this.applicationContext));
}
那么它什么时候被 start() ?——在⼯序 12 的 getLifecycleProcessor().onRefresh() ⾥。

⽽它的 phase 挑得极有讲究:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/context/WebServerApplicationContext.java:40

int GRACEFUL_SHUTDOWN_PHASE = SmartLifecycle.DEFAULT_PHASE - 1024;
int START_STOP_LIFECYCLE_PHASE = GRACEFUL_SHUTDOWN_PHASE - 1024;
SmartLifecycle.DEFAULT_PHASE 是 Integer.MAX_VALUE ( [framework] spring-
context/src/main/java/org/springframework/context/SmartLifecycle.java:82 ),所以这两个 phase 都是相对默认值的负偏移,⽽且 START_STOP ⽐

GRACEFUL_SHUTDOWN 还⼩ 1024。

⽅向别记反,回源看排序容器就⼀⽬了然:

// [framework] spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java:365

private void startBeans(boolean autoStartupOnly) {
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
Map<Integer, LifecycleGroup> phases = new TreeMap<>(); //升序 → phase⼩的先 start

...

}

// [framework] .../DefaultLifecycleProcessor.java:436

private void stopBeans(boolean pauseableOnly) {
Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
Map<Integer, LifecycleGroup> phases = new TreeMap<>(Comparator.reverseOrder()); //降序 → phase⼤的先 stop

...

}
⼀个裸 TreeMap ,⼀个 reverseOrder() 的 TreeMap 。phase ⼩的先 start、后 stop。

于是这三个常量排出来的真实次序是:

启动: webServerStartStop (MAX−2048)→ webServerGracefulShutdown (MAX−1024)→ 其余默认 phase 的 SmartLifecycle(MAX)。

停机:其余组件 → webServerGracefulShutdown → webServerStartStop 。

那 1024 的差值,唯⼀板上钉钉的效果是停机侧:优雅停机那⼀环必须先动(拒绝新请求、等在途请求跑完),然后才轮到真正把容器停掉。"先劝客、后关⻔"这个次序,被编码进了两个常量的减法⾥。

但启动侧的效果值得说句实话:Web 容器是所有⾃动启动组件⾥最先 start 的——端⼝先开,业务侧的 SmartLifecycle 后就位。它并不像很多⼈以为的那样"等⼀切就绪才开⻔"。真

正管"什么时候开始收正经流量"的是另⼀套东⻄: ReadinessState.ACCEPTING_TRAFFIC 要到 ApplicationReadyEvent 才⼴播( [boot] core/spring-
boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java:111 ),那已经是 refresh 之后、 callRunners 之后的事了。phase

管的是启停次序,readiness 探针管的才是流量闸⻔——两码事,别混。

它还带了⼀句 isPauseable() { return false; } ( [boot] .../servlet/context/WebServerStartStopLifecycle.java:67-69 )——对应 Framework 7 新增的
pause/restart 语义( [framework] .../AbstractApplicationContext.java:1601-1611 , pause() / restart() 的 javadoc 标 @since 7.0 )。Web 容器明确表态:别把我

pause,我要么开着要么关着。

🦴 ⻣灰级细节:Boot 为什么必须把 refresh() 覆写成 final。

// [boot] .../ServletWebServerApplicationContext.java:141@Override

public final void refresh() throws BeansException, IllegalStateException {
try {
super.refresh();
}
catch (RuntimeException ex) {
WebServer webServer = this.webServer;
if (webServer != null) {
try { webServer.stop(); webServer.destroy(); }
catch (RuntimeException stopOrDestroyEx) { ex.addSuppressed(stopOrDestroyEx); }
}
throw ex;
}
}

这⼀段是 Boot 在给 Framework 打补丁,⽽且是⼀处真实的分层漏点。

Framework 的失败回滚只会 destroyBeans() ——它认识的只有"单例池⾥可销毁的 bean"。可 Tomcat 是被 registerSingleton 塞进去的、由 this.webServer 这个普通字段持有的外部资源:端⼝已经占了,线程池已经起了,⽽ destroySingletons() 对它⼀⽆所知。于是⼯序 9 之后、⼯序 12 之前任何⼀处炸掉,Framework 会⼲⼲净净地销毁所有bean,然后留下⼀个还在监听 8080 端⼝的 Tomcat 扬⻓⽽去。

Boot 只能在外⾯再套⼀层 try-catch ⾃⼰收⼫,还得加 final 防⽌⼦类把这层兜底覆盖掉。这不是 Boot 写得不好,是 Framework 的失败模型有个前提假设——"context ⾥的⼀切都是 bean"——⽽这个假设在内嵌容器时代就不成⽴了。⼀层⽤ final 封死另⼀层的扩展点,通常都是下层能⼒不⾜的信号。

九、⼯序 10 · registerListeners() —— 接线,然后冲刷缓冲区// [framework] .../AbstractApplicationContext.java:915

protected void registerListeners() {

// Register statically specified listeners first.

for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}

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

String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}

// Publish early application events now that we finally have a multicaster...

Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null; // :930
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}

三段,每段都有⼀句"不能颠倒"的理由。

第⼆段那个 false ( getBeanNamesForType(ApplicationListener.class, true, false) 的第三个参数是 allowEagerInit )是全章我最欣赏的⼀处克制。注释把理由写死

了:"We need to leave all regular beans uninitialized to let post-processors apply to them!"——为了找监听器⽽提前造器,等于让这些器漏掉后⾯的⼯序。宁可找不全,也不提前造。

代价当然存在:由 FactoryBean 产出的监听器,在这⾥可能识别不到。兜底靠的正是⼯序 6 挪到队尾的那个 ApplicationListenerDetector ——它会在实例化之后把漏⽹的补

捞回来( [framework] .../ApplicationListenerDetector.java:74-95 )。两处设计在这⾥对上了暗号。
补捞也有边界:⾮单例的内部 bean 只会得到⼀条 warn( :83-92 ),原⽂是 "Only top-level listener beans are allowed to be of non-singleton scope." ——它⽼实承

认⾃⼰接不住。

第三段最⻅功夫:先把 earlyApplicationEvents 置 null( :930 ),再遍历⼴播。

顺序反了会怎样?如果先⼴播再置 null,那么"早期事件的监听器在处理事件时⼜发了⼀个新事件"——这个新事件会再次掉进缓冲区,⽽缓冲区⻢上就要被置 null 丢弃了。事件凭空蒸发。先置 null,则 publishEvent 的第⼀个分⽀⽴刻失效,新事件⾛正常⼴播通道,⼀切正常。

两⾏代码的顺序,决定了⼀整类"事件偶尔丢⼀个"的灵异现象存在与否。

⼗、⼯序 11 · finishBeanFactoryInitialization() —— 唯⼀真正的重活

前⾯⼗道加起来的耗时,通常都⽐不过这⼀道。这⾥才是把满屋⼦图纸变成满屋⼦器的地⽅。

// [framework] .../AbstractApplicationContext.java:943

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
beanFactory.prepareSingletonBootstrap(); // :945
if (beanFactory.containsBean(BOOTSTRAP_EXECUTOR_BEAN_NAME) && ...) { ... } // :948
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && ...) { ... } // :955
if (!beanFactory.hasEmbeddedValueResolver()) { // :964
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
String[] initializerNames = beanFactory.getBeanNamesForType(BeanFactoryInitializer.class, false, false); // :969
for (String initializerName : initializerNames) { ... }
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); // :975
for (String weaverAwareName : weaverAwareNames) { ... }
beanFactory.setTempClassLoader(null); // :989
beanFactory.freezeConfiguration(); // :992
beanFactory.preInstantiateSingletons(); // :995
}

九步,最后⼀⾏才是主菜。前⼋步全是"上菜前把厨房收拾⼲净"。

第⼀步就是本基线的新东⻄。 prepareSingletonBootstrap() ——很多讲 5.x/6.0 的⽂章⾥,这⼀格的第⼀步是装 conversionService。接⼝默认⽅法在 [framework]

spring-beans/src/main/java/org/springframework/beans/factory/config/ConfigurableListableBeanFactory.java:165 ,javadoc 标 @since 6.2.12 (这是源码⾥

的 @since 标签,不是我查的发布历史),语义是"把当前线程标记为主引导线程,后台线程适⽤宽松锁"。实现只有⼀⾏赋值( [framework]

.../DefaultListableBeanFactory.java:1096-1099 )。

第 964 ⾏那个兜底的占位符解析器,是⼀处不显眼的暗礁。 只在没⼈装过 embedded value resolver 时才装,⽽它装的那个 lambda 只认

Environment: getEnvironment().resolvePlaceholders(strVal) 。它和 PropertySourcesPlaceholderConfigurer 的⾃定义前缀、

ignoreUnresolvablePlaceholders 等⼀切配置毫⽆关系。也就是说,同⼀个 ${...} 语法,在配了 configurer 和没配 configurer 的两种应⽤⾥,⾏为可能不同。

第 969 ⾏那个 BeanFactoryInitializer ,让我当场推翻了⾃⼰的⼀条笔记。

我原本的素材⾥写着"全仓 grep,framework 和 boot 的 main 源码⾥没有任何实现类,纯扩展点"。回源⼀ grep,主源码⾥确实有⼀个:

// [framework] spring-test/src/main/java/org/springframework/test/context/support/DynamicPropertyRegistrarBeanInitializer.java:41

public class DynamicPropertyRegistrarBeanInitializer implements BeanFactoryInitializer<ListableBeanFactory>, EnvironmentAware {

它做的事( :64-81 )⾮常漂亮:在批量造器开始之前,把所有 DynamicPropertyRegistrar bean 提前实例化,让它们往 Environment ⾥注册⼀个DynamicValuesPropertySource 。这就是测试⾥ @DynamicPropertySource 那套"⽤ Testcontainers 随机端⼝覆盖配置"能⽣效的物理原因——它必须抢在任何业务 bean 读取 ${...} 之前完成,⽽⼯序 11 的第 5 步正好是最后的窗⼝期。

笔记错了,以源码为准,记在这⼉。

主菜 preInstantiateSingletons() 在 [framework] spring-

beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java:1102-1151 。从 refresh 的视⻆,只需记三件事:

1. 它遍历的是 beanDefinitionNames 的副本( :1109 ),注释说明是为了容忍"init ⽅法⾥⼜注册了新定义"这种事——"While this may not be part of the regular factory

bootstrap, it does otherwise work fine." ⼀句不咸不淡的话,承认了这是灰⾊地带但不封死。

  1. 后台并⾏初始化默认是关的。 mbd.isBackgroundInit() 且配了 executor 才⾛ CompletableFuture.runAsync ;没配 executor 时,只打⼀条 info ⽇志然后⽼⽼实实回
落主线程: java // [framework] .../DefaultListableBeanFactory.java:1184 logger.info("Bean '" + beanName + "' marked for background
initialization " + "without bootstrap executor configured - falling back to mainline initialization"); 这条⽇志是排查"我标了 background init 怎

么没并⾏"的唯⼀线索。⽽ bootstrapExecutor 的 javadoc 也直说了:"If none is supplied, no background bootstrapping will be active."

Boot 在这⾥补了⼀⼿: [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/task/TaskExecutorConfigurations.java:214-231 注册了个 BFPP,如果容器⾥没有bootstrapExecutor 但有 applicationTaskExecutor ,就给后者加⼀个别名指过去。所以裸 Framework 应⽤默认找不到 executor,Boot 应⽤通常找得到。 3. 全部造完之后,

还要再遍历⼀遍触发 SmartInitializingSingleton.afterSingletonsInstantiated() ( :1142-1150 ,埋点名 spring.beans.smart-initialize )。 @EventListener 的

注册、 @Scheduled 的登记都发⽣在这⾥——仍在⼯序 11 之内,早于 ContextRefreshedEvent 。

第三点值得单独强调,因为它纠正⼀个很常⻅的误解:" @EventListener 是在 ContextRefreshedEvent 时才注册的"——不是。它⽐那更早⼀格。所以⼀个监听ContextRefreshedEvent 的 @EventListener ⽅法能收到事件,不是巧合,是顺序算好的。

⾄于 freezeConfiguration() ( :992 ):从这⼀刻起图纸封板,不再期待变更,可以放⼼地激进缓存。它是"启动完就别再动 BeanDefinition"这条铁律的物理执⾏点。

⼗⼀、⼯序 12 · finishRefresh() —— 收摊,起⽕,鸣锣// [framework] .../AbstractApplicationContext.java:1003

protected void finishRefresh() {

// Reset common introspection caches in Spring's core infrastructure.

resetCommonCaches(); // :1005
// Clear context-level resource caches (such as ASM metadata from scanning).
clearResourceCaches(); // :1008

// Initialize lifecycle processor for this context.

initLifecycleProcessor(); // :1011

// Propagate refresh to lifecycle processor first.

getLifecycleProcessor().onRefresh(); // :1014

// Publish the final event.

publishEvent(new ContextRefreshedEvent(this)); // :1017
}

五⾏,件件是终局动作。

前两⾏是丢垃圾。 resetCommonCaches() ( :1042 ,javadoc 标 @since 4.2 )清掉 ReflectionUtils / AnnotationUtils / ResolvableType /
CachedIntrospectionResults 四个缓存; clearResourceCaches() ( :1050 )连带清掉 PathMatchingResourcePatternResolver 的缓存——注释点名 such as ASM

metadata from scanning ,即包扫描期攒下的那⼀⼤堆字节码元数据,在这⼀刻全部丢掉。启动期这些缓存是加速器,启动完就是纯粹的内存负担。

这⾥⼜是⼀处与旧资料的分歧,标出来: 很多讲 5.x/6.x 的流程图把 resetCommonCaches() 画在 refresh 的 finally 块⾥。本基线不是——它在 finishRefresh() 的开头,以

及 cancelRefresh() ⾥( :1029 )。refresh 的内层 finally 只剩⼀⾏ contextRefresh.end() ( :655 )。
第三⾏是最后⼀个"特殊 bean"就位。 initLifecycleProcessor() ( :880-898 )和⼯序 7/8 ⼀个模⼦。它到第 12 步才初始化,所以 getLifecycleProcessor() ( :492 )在此

之前被调⽤⼀律抛 IllegalStateException 。

第四⾏才是"起⽕"。 前⾯说过,Boot 的 Tomcat 就在这⼀⾏被真正 start() :

// [framework] spring-context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java:295@Override

public void onRefresh() {
if (checkpointOnRefresh) {
checkpointOnRefresh = false;
new CracDelegate().checkpointRestore();
}
if (exitOnRefresh) {
Runtime.getRuntime().halt(0);
}
this.stoppedBeans = null;
try {
startBeans(true);
}
catch (ApplicationContextException ex) {

// Some bean failed to auto-start within context refresh:

// stop already started beans on context refresh failure.

stopBeans(false);
throw ex;
}
this.running = true;
}
startBeans(true) 的那个 true 是 autoStartupOnly ( [framework] .../DefaultLifecycleProcessor.java:365 )——只启动 isAutoStartup() 为真的

SmartLifecycle 。普通的 Lifecycle bean 在 refresh ⾥不会被⾃动 start,得等你显式调 context.start() ( :1590 )。这是"我实现了 Lifecycle 怎么没被启动"的答案。

⚠ ⽽中间那两个 if,藏着⼀颗能吓死⼈的雷。

spring.context.exit=onRefresh 会让 JVM 在这⾥执⾏ Runtime.getRuntime().halt(0) ( :300-302 )。注意是 halt ,不是 System.exit ——它不跑 shutdown

hook、不关容器、不给任何⼈告别的机会,进程直接原地消失。属性名常量在 [framework] .../DefaultLifecycleProcessor.java:101 ,值常量在 :109 ,javadoc 标 @since6.1 。

它的正当⽤途是给 AOT/CRaC 场景做"启动到这⾥就够了,测⼀下"。但如果有⼈把这个属性误配进了⽣产环境,你会看到⼀个进程启动到⼀半、⽇志戛然⽽⽌、退出码 0、没有任何异常栈——教科书级的"灵异事件"。⽽ checkpointOnRefresh 是个 static 字段( :112-113 ),CRaC 检查点全 JVM 只做⼀次。

最后⼀⾏才鸣锣。 ContextRefreshedEvent 排在这个位置是有严格语义的:"所有⾮懒加载单例都已就绪"。它必须在 preInstantiateSingletons() 之后,否则这句承诺就是假的。

⚠ 但这⼀锣会传到隔壁。 publishEvent 的最后⼀段( :452-460 )会把事件向⽗ context 传播。于是在 Spring MVC 那种⽗⼦容器的架构⾥,⽗容器⾥的监听器会收到⼦容器的

ContextRefreshedEvent ——"我的监听器为什么被调了两次"这个经典问题,答案就是这⼋⾏。

⼗⼆、为什么必须是这个顺序⾛完全程,把⼗⼆道压成五句因果,顺序问题就不再需要背了:

  1. 要有作坊,才能谈作坊⾥的事。(1→2)
  1. 要先给作坊装好"总装房外挂"——Aware、可解析依赖、默认单例——后⾯注册进来的任何东⻄才享受得到。(2→3→4)
  1. 改图纸的⼈必须全部先于过⼿的⼈注册,⽽过⼿的⼈必须全部先于任何业务器被造出来。 否则就出现"漏过 BPP 的器",也就是 BeanPostProcessorChecker 那条警告要抓的病。(5→6→11)
  1. 基础设施 bean ⾃⼰也是 bean,必须在业务单例批量出⽣之前就位;⽽它们之间还有单向依赖——监听器可以⽤ MessageSource,MessageSource 不可以发事件。
(7→8→10)
  1. "宣布开张"必须是最后⼀件事。 ContextRefreshedEvent 的语义就是"全都好了",所以它只能排在 preInstantiateSingletons() 之后。(11→12)

顺序不是⻛格问题,是依赖问题。 每⼀道⼯序都只依赖它前⾯那⼏道的产物,这条链⼀旦成⽴,顺序就是唯⼀的——你甚⾄可以说, refresh() 那 81 ⾏不是被"设计"出来的,是被这五条约束推导出来的。

⽽⼯序 4 和⼯序 9 两个空钩⼦,恰好卡在"BFPP 之前"和"批量造器之前"这两个最值钱的插槽上。Template Method 的两个逃⽣舱,位置挑得没得挑。

但也就这两个。 这是我对这⼀⻚最实在的⼀处不满:⼗⼆道⼯序是硬编码在⼀个 final 到⻣⼦⾥的调⽤序列⾥的,没有任何注册式的"我想插在⼯序 7 和 8 之间"的机制。你要么⽤这两个钩⼦,要么覆写整个 refresh() ——⽽ Boot 正是被逼着⾛了后⼀条路,还得加 final 防⽌别⼈再覆写⼀遍。⼀个⼆⼗五年没变过的⽅法,它的稳定性有多可贵,它的僵硬就有多真实。

⼗三、失败了怎么收场// [framework] .../AbstractApplicationContext.java:628

catch (RuntimeException | Error ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}

// Stop already started Lifecycle beans to avoid dangling resources.

if (this.lifecycleProcessor != null && this.lifecycleProcessor.isRunning()) {
try { this.lifecycleProcessor.stop(); }
catch (Throwable ex2) {
logger.warn("Exception thrown from LifecycleProcessor on cancelled refresh", ex2);
}
}

// Destroy already created singletons to avoid dangling resources.

destroyBeans(); // :645

// Reset 'active' flag.

cancelRefresh(ex); // :648

// Propagate exception to caller.

throw ex; // :651
}

先纠三条⼏乎⼈⼈记错的细节:

catch 的是 RuntimeException | Error ,不是⽼资料⾥说的 BeansException ,也不是 Throwable (受检异常不在此列)。
cancelRefresh 的签名在本基线是 protected void cancelRefresh(Throwable ex) ( :1025 ),全仓没有 BeansException 的旧重载残留。

异常原样抛出,不包装( :651 )。你在 main ⾥看到的堆栈顶端是什么,refresh ⾥炸的就是什么。

三步回滚的顺序也有讲究。 先停已启动的 Lifecycle bean,⽽且是直接读字段 this.lifecycleProcessor ——不⾛会抛异常的 getLifecycleProcessor() ;整段⽤ try/catch包住,⼆次异常只 warn。回滚代码的第⼀美德是不掩盖原始异常,这⾥做到了。

然后 destroyBeans() → destroySingletons() ,把已经造好的器全部销毁。这⼀步的效果有测试直接背书: [framework] spring-context/src/test/java/org/springframework/context/support/GenericApplicationContextTests.java:319-332 断⾔ bean 会先 initialized 再destroyed ; :334-348 更狠,连 SmartInitializingSingleton 阶段才失败,也照样把之前造好的全部销毁。

但这套回滚有三个洞,⽽且洞洞⻅⾎:

洞⼀:⼯序 1、2、3 的失败根本进不了这个 catch。 回到开头那根刺—— try 开在第 598 ⾏。 prepareRefresh() 已经在第 672 ⾏把 active 置了 true ;这时如果

obtainFreshBeanFactory() 抛异常(XML 解析失败、或者 GenericApplicationContext 被⼆次 refresh),或者 prepareBeanFactory() 出事,那么:
destroyBeans() 不执⾏、 cancelRefresh() 不执⾏ → active 永远停在 true , isActive() 从此开始撒谎;

contextRefresh.end() 也不执⾏(它在内层 finally ⾥)→ ApplicationStartup 的埋点永远悬空,你的启动耗时统计⾥会多出⼀段没有终点的 span。

这是⼀处看似对称、其实并不对称的设计。我不认为它是有意的——把 try 往上挪三⾏,代价⼏乎为零。但它就在那⼉,已经在那⼉很久了。

洞⼆:失败即报废。 前⾯说过, GenericApplicationContext.refreshed 不复位。

洞三: closeBeanFactory() 和 onClose() 不在失败路径上。 它们只出现在 doClose() ⾥( :1211 、 :1214 )。所以⼦类持有的⼀切⾮ bean 的外部资源——最典型就是Boot 的 Tomcat——Framework ⼀概不管。这正是上⼀节 Boot 必须⾃⼰覆写 refresh() 兜底的原因。

顺带看⼀眼镜像: doClose() ( :1182-1233 )⼏乎是 refresh 的倒放——发 ContextClosedEvent → lifecycleProcessor.onClose() → destroyBeans() →
closeBeanFactory() → onClose() → resetCommonCaches() → 把监听器集合复位到 pre-refresh 快照 → 三个内部委托置 null → active.set(false) 。⼊⼝守卫是
if (this.active.get() && this.closed.compareAndSet(false, true)) ( :1184 ),所以 close 是幂等的。

对⽐之下,失败路径的不完整就更明显了: doClose 做了七件事, catch 块只做了三件。

🦴 ⻣灰级细节

其⼀:2026 年的主⼲⾥,还留着为 WebLogic 8.1 打的补丁,⽽且写着报告⼈的名字。

// [framework] .../AbstractApplicationContext.java:180

static {

// Eagerly load the ContextClosedEvent class to avoid weird classloader issues

// on application shutdown in WebLogic 8.1. (Reported by Dustin Woods.)
ContextClosedEvent.class.getName();
}

⼀个静态块,⼀句提前加载,⼀个署名。WebLogic 8.1 早已是化⽯,这⾏代码还在。类的 @since 标签是 January 21, 2001 ( :136 )——连⽇期格式本身都是化⽯。

其⼆:那把锁换了,⽽且换得很有讲究。

// [framework] .../AbstractApplicationContext.java:215/** Synchronization lock for "refresh" and "close". */

private final Lock startupShutdownLock = new ReentrantLock();

⽆数博客的流程图上写着 synchronized (this.startupShutdownMonitor) 。全仓 grep startupShutdownMonitor ,零命中。 那个字段在本基线上已经彻底消失了。

换成 ReentrantLock 的直接收益很实在: synchronized 会 pin 住虚拟线程的载体线程,⽽ ReentrantLock 不会。⼀个⼆⼗五年的⽼类,为了虚拟线程改了⼀把锁——这⼤概是本章最能说明"Spring 还活着"的⼀处证据。

其三:关机钩⼦会猜你是不是调了 System.exit 。

// [framework] .../AbstractApplicationContext.java:1118

private boolean isStartupShutdownThreadStuck() {
Thread activeThread = this.startupShutdownThread;
if (activeThread != null && activeThread.getState() == Thread.State.WAITING) {

// Indefinitely waiting: might be Thread.join or the like, or System.exit

activeThread.interrupt();
try {

// Leave just a little bit of time for the interruption to show effect

Thread.sleep(10);
}
catch (InterruptedException ex) { Thread.currentThread().interrupt(); }
if (activeThread.getState() == Thread.State.WAITING) {

// Interrupted but still waiting: very likely a System.exit call

return true;
}
}
return false;
}

关机钩⼦拿不到锁时,不会硬等——它以 100ms 为粒度轮询 tryLock ( :1095-1112 ),每轮都来问⼀句"启动线程是不是卡死了"。判定⼿法堪称侦探:看它是不是 WAITING → 捅它⼀⼑(interrupt) → 睡 10 毫秒 → 再看⼀眼 → 还在 WAITING ,那⼋成是有⼈在组件⾥调了 System.exit ,于是直接把 active 置 false、放弃关闭,免得两条线程互相等到天荒地⽼。

⼀段基于线程状态 + 中断响应的启发式推断,只为了处理"⽤户在 @PostConstruct ⾥调了 System.exit "这种荒唐场景。这是全类最像侦探⼩说的⼗⼏⾏。

⚠ 暗礁清单

  1. 假 active——⼯序 1/2/3 失败时 active 停在 true, isActive() 撒谎,启动埋点悬空。( :598 那个 try 的位置)
  1. 失败即报废—— GenericApplicationContext 的 refreshed 是⼀次性 CAS 闸⻔且失败不复位,Boot 应⽤⽆法重试 refresh。
  1. 事件静默丢失——refresh 前、close 后 publishEvent 不报错也不⽣效。( :444-450 、 :1226 )
  1. 事件默认同步、⽆ errorHandler——⼀个监听器抛异常,整条事件链当场断掉并冒泡给发布者。
  1. 事件向⽗容器传播——⽗⼦容器架构下监听器"被调两次"。( :452-460 )
  1. MessageSource 不能发事件——Spring 亲⼝写在 javadoc ⾥的取舍。( :374 )
  1. registerSingleton 绕过全部 BPP——默认 messageSource / multicaster / lifecycleProcessor,以及 Boot 的 webServerStartStop 、springApplicationArguments ,都不会被 AOP 代理。
  1. FactoryBean 产出的监听器可能漏注册——只能靠队尾的 ApplicationListenerDetector 补捞,⾮单例内部 bean 只有⼀条 warn。
9. spring.context.exit=onRefresh 会 Runtime.halt(0) ——⼯序 12 中途直接杀 JVM,不跑 shutdown hook,退出码 0,零异常栈。
  1. containsLocalBean 与 containsBean 的不对称——environment 四件套不看⽗容器,conversionService / bootstrapExecutor / loadTimeWeaver 看⽗容器。
11. 兜底的 embedded value resolver 只认 Environment——与 PropertySourcesPlaceholderConfigurer 的⾃定义配置⽆关。( :964-966 )
  1. backgroundInit 没配 executor 时静默降级——只有⼀条 info ⽇志。
  1. 编程式注册的 BFPP 列表不清空—— beanFactoryPostProcessors ( :203 )在可重复 refresh 的 context 上会被反复执⾏。
  1. Framework 的失败回滚认不出"⾮ bean 的外部资源"——这就是 Boot 必须把 refresh() 覆写成 final 来 stop/destroy Tomcat 的原因。

🎯 三句带⾛1. refresh() 只有 81 ⾏,不⼲活,只钉顺序:先建⼯⼚ → 装上下⽂外挂 → 改 BeanDefinition 的先跑完 → 注册所有 BeanPostProcessor → 建基础设施 bean → 最后才批量实例化单例 → 发 ContextRefreshedEvent 。顺序是依赖推导出来的,不是⻛格。

2. 失败路径不完整: try 开在第 598 ⾏,前三步失败不会 destroyBeans 也不会 cancelRefresh , active 会停在 true; GenericApplicationContext 失败后不复

位,context 直接报废;外部资源(内嵌 Tomcat)Framework ⼀概不管,得 Boot ⾃⼰覆写 refresh() 兜底。

3. 本基线三处必须更新的旧知识:锁是 ReentrantLock 不是 synchronized (startupShutdownMonitor) ; resetCommonCaches() 在 finishRefresh() 开头⽽⾮
refresh 的 finally;Boot 4 不再覆写 finishRefresh() ,Tomcat 由 WebServerStartStopLifecycle 在⼯序 12 的 lifecycleProcessor.onRefresh() ⾥启动。

承上启下⼗⼆道⼯序⾥,有两道我⼀直在绕过去。

⼯序 1 的第 684 ⾏, initPropertySources() ——⼀个在 AbstractApplicationContext ⾥彻底空着的⽅法,javadoc 只说"把 stub 属性源换成真的"。⼯序 1 的第 688⾏, getEnvironment().validateRequiredProperties() ——整个启动流程⾥必填属性唯⼀的校验点。⼯序 3 的第 764 ⾏,把 environment 注册成默认单例。⼯序 11 的第964 ⾏,那个"只认 Environment"的兜底占位符解析器。还有刚才那位 DynamicPropertyRegistrarBeanInitializer ,它抢在批量造器之前挤进去,就为了往 Environment ⾥塞⼀个属性源。

五处,分散在四道⼯序⾥,全指向同⼀个东⻄:那个从始⾄终坐在总装房⻆落、谁都要来问它⼀句的 Environment 。

它是怎么把 JVM 参数、环境变量、 application.yml 、命令⾏、 @PropertySource 、Testcontainers 的随机端⼝……这⼀⼤堆来源各异的配置,排成⼀条有先后、可覆盖、可查询的队列的?为什么 ${server.port} 在有的地⽅解析得出、有的地⽅解析不出?为什么"我明明改了配置⽂件却不⽣效"永远排在 Spring 问题榜前三?

下⼀章,ch16 · Environment 与 PropertySource——那条决定"谁说了算"的优先级链。