源码小说CodeStory
登录
上一章

39,583 字 · 约 99 分钟

下一章
字体

主题

版式

第37章 卷十一 · 一句话开张 · 开张前后的插手点

这就是"约定优于配置"在源码层⾯的真身:它不是省掉了什么,它是把你本来要⾃⼰写的样板,固化成了⼀条谁都改不动的顺序。

⚠ 暗礁清单(本章遇到的,按危险度排)

1. listeners.starting() 在 try 之外( :313 vs :314 )。早期 listener 抛异常 → 不⾛ handleRunFailure 、没有失败分析、不发 ApplicationFailedEvent ,只有

⼀个裸栈往上冒。这是整段 run ⾥唯⼀⼀处没有安全⽹的代码。

2. ready 阶段炸了,不发 ApplicationFailedEvent 。 :339 的 handleRunFailure(context, ex, null) 第三个参数是 null,⽽ :811 是 if (listeners !=

null) 才通知。静默。

3. ApplicationReadyEvent 可能根本不发。 :334 有个 context.isRunning() 守卫,⽽它等于 lifecycleProcessor != null &&
lifecycleProcessor.isRunning() ( [framework] spring-
context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:1613-1616 )。如果某个 Runner 把容器关了,或者 lifecycle

没跑起来,你的 ready 监听器就是不触发。 这是这类⽞学问题的头号嫌疑⼈。

4. spring.main.* 覆盖你代码⾥的 setter,因为 bind( :361 )晚于你在 main ⾥调 setter。
5. 同时实现 ApplicationRunner + CommandLineRunner 的 bean 会被调两次( :787 与 :790 是两个独⽴ if)。
  1. 循环依赖 / bean 覆盖默认与裸 Framework 相反,迁移时第⼀个红屏。
7. setEnvironment() 之后 Boot 不再帮你换 Environment 类型( :362 的 !this.isCustomEnvironment )。
  1. EnvironmentConverter 反射失败静默降级,⼀⾏⽇志都没有。
  1. banner.txt 会被依赖 jar 污染,⽽防御只硬编码了 liquibase-core ⼀家。
10. shutdownHook 是 static ( :207 ),跨 SpringApplication 共享——测试⾥反复 run() 时要留神。
  1. BootstrapContext 以 Class 为 key,⼀个类型只能存⼀个实例;⽽且对已经被取出过的类型再 register ,会直接抛 "... has already been created" 。
  1. applyInitializers 要求泛型可解析,lambda 或裸类型的 initializer 直接 Assert 失败。

🎯 三句带⾛

1. SpringApplication.run() 没有改动 refresh() 的任何⼀⾏—— [boot] core/spring-
boot/src/main/java/org/springframework/boot/SpringApplication.java:755-757 整个⽅法体只有 applicationContext.refresh(); ;Boot 做的全部

是"refresh 之前把参数备⻬、refresh 之后把⼈送到岗、两侧各拴⼀根安全绳"。

  1. Boot 把 Framework 的两个默认值反着设了: allowCircularReferences 与 allowBeanDefinitionOverriding 在 Framework 侧默认允许,在 Boot 侧默认
false ( [boot] .../boot/SpringApplication.java:388 、 :390 + [boot] .../boot/ApplicationProperties.java:43 、 :49 )。同⼀份配置类,两种容器可能

⼀个跑得起来、⼀个直接报错。

  1. @EventListener 收不到 ApplicationStartingEvent 等前四个事件,因为它们由 EventPublishingRunListener ⾃带的 initialMulticaster ⼴播,⽽容器的
multicaster 要到 refresh() 的第 8 道⼯序才存在;要收早期事件只能⾛ spring.factories 或 addListeners(...) 。

承上启下本章从头到尾都在跟同⼀批东⻄打交道: spring.factories ⾥读出来的 ApplicationContextInitializer 、 ApplicationListener 、SpringApplicationRunListener 、 BootstrapRegistryInitializer ,还有两个本基线新⾯孔—— WebApplicationType.Deducer 与 ApplicationContextFactory 。我⼀路只做了⼀件事:把它们钉在时间轴上的某⼀格,说清"谁在什么时刻被叫到"。

可我⼀直绕过了三个更要命的问题:

它们各⾃到底能⼲什么、不能⼲什么? ⼀个 ApplicationContextInitializer 能改图纸吗?⼀个 EnvironmentPostProcessor 能拿到容器吗?

它们之间谁先谁后? 我提到过 +10 早于 +20 、 @Order(10) 先于 @Order(20) ,但完整的排序规则是什么?同⼀格⾥撞⻋了算谁的?

最要命的⼀条:本基线到底⽤哪套加载机制? 这⼀章⾥我⼝⼝声声说" spring.factories ",可 Boot 4 早就有了另⼀套 META-INF/spring/*.imports 。两套并存,各管各的⼀摊,⽽"哪个类型⾛哪套"这件事,⽹上关于 Boot 3 的⽂章已经不能照抄了。

下⼀章(ch36)就把这⼏个问题⼀次问清楚:开张前后的插⼿点——每⼀类扩展点的能⼒边界、两套发现机制的分⼯、以及⼀张回源核实过的完整排序表。

从"什么时候被叫到",⾛向"被叫到之后你能⼲什么"。

开张前后的插⼿点"我不是⼀组回调,我是⼀条轴。 你写的每⼀个扩展点都不重要,重要的是它被钉在我身上的哪⼀格—— 早⼀格,你⼿⾥空空如也;晚⼀格,你想改的东⻄已经定型了。"

—— SpringApplication.run(String...) 的⾃⽩

⼀个每年都要被重新问⼀遍的问题有⼈写了这么⼀段:

@Component

public class MyListener implements ApplicationListener<ApplicationStartingEvent> {
@Override public void onApplicationEvent(ApplicationStartingEvent event) {

System.out.println("我要在最早的时候⼲点事");

}
}

跑起来,什么也没打印。没有报错,没有警告,⽇志⾥⼲⼲净净。

这不是 bug。这是本章要讲的整件事的⼀个缩影:Boot 的扩展点不是⼀组平⾏的接⼝,⽽是⼀条时间轴上的六个钉⼦。你把监听器写成 @Bean ,等于把它挂在了轴的中段;⽽ApplicationStartingEvent 是轴的第⼀格发出的——那时候连总装房都还没盖起来,谁去登记你这个 @Bean ?

所以这⼀章我们只做⼀件事:把轴画准,把六个钉⼦的位置钉死,再回答"谁负责去 classpath 上把这些扩展点找出来"。

第⼆个问题在 Boot 4 上尤其容易被写错。⽹上关于"spring.factories 已经废弃了"的⽂章⼀抓⼀⼤把,但本基线(spring-boot 4.2.0-SNAPSHOT,commit 87cacdaa )的源码不是这么说的。我们会⼀条条把它翻出来。

⼀、轴的全⽂: run() 的四⼗⾏先把权威⽂本摊开。整条轴就住在这⼀个⽅法⾥:

public ConfigurableApplicationContext run(String... args) { // :304
Startup startup = Startup.create(); // :305
if (this.properties.isRegisterShutdownHook()) { // :306
SpringApplication.shutdownHook.enableShutdownHookAddition(); // :307
}
DefaultBootstrapContext bootstrapContext = createBootstrapContext(); // :309 ←① BootstrapRegistryInitializer
ConfigurableApplicationContext context = null; // :310
configureHeadlessProperty(); // :311
SpringApplicationRunListeners listeners = getRunListeners(args); // :312 ←② RunListener在此实例化
listeners.starting(bootstrapContext, this.mainApplicationClass); // :313 ←⚠ 在 try之外
try { // :314
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext,
applicationArguments); // :316 ←③ EnvironmentPostProcessor
Banner printedBanner = printBanner(environment); // :317
context = createApplicationContext(); // :318
context.setApplicationStartup(this.applicationStartup); // :319
prepareContext(bootstrapContext, context, environment, listeners,
applicationArguments, printedBanner); // :320 ←④ ApplicationContextInitializer
refreshContext(context); // :321
afterRefresh(context, applicationArguments); // :322
Duration timeTakenToStarted = startup.started(); // :323
if (this.properties.isLogStartupInfo()) { /* ... */ } // :324-326
listeners.started(context, timeTakenToStarted); // :327
callRunners(context, applicationArguments); // :328 ←⑥ Application/CommandLineRunner
}
catch (Throwable ex) { // :330
throw handleRunFailure(context, ex, listeners); // :331
}
try { // :333
if (context.isRunning()) { // :334
listeners.ready(context, startup.ready()); // :335
}
}
catch (Throwable ex) { // :338
throw handleRunFailure(context, ex, null); // :339 ←第三参是 null
}
return context; // :341
}

[boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:304-342 。

四⼗⾏不到,⼀座坊从空地到开⻔营业的全过程都在这⾥。把它折成⼀张轴:

JVM 起 → new SpringApplication(...) :274-284
├─ WebApplicationType.deduce() [SPI] :278
├─ 扫 BootstrapRegistryInitializer [spring.factories] :279-280
├─ 扫 ApplicationContextInitializer [spring.factories] :281
├─ 扫 ApplicationListener [spring.factories] :282
└─ StackWalker 翻栈找 main 类 :283
run(args)
├─ ① BootstrapRegistryInitializer.initialize (⽆ Environment、⽆容器) :309
├─ ② 实例化 SpringApplicationRunListener :312
├─ listeners.starting → ApplicationStartingEvent ⚠ try 之外 :313
├─ prepareEnvironment :316
│ └─ listeners.environmentPrepared → ApplicationEnvironmentPreparedEvent
│ └─ ③ 所有 EnvironmentPostProcessor 按序跑(ConfigData 在最后)
├─ createApplicationContext (容器诞⽣,未 refresh) :318
├─ prepareContext :320
│ ├─ ④ applyInitializers (bean 定义还没加载!) :393
│ ├─ listeners.contextPrepared → ApplicationContextInitializedEvent :394
│ ├─ load(context, sources) ← bean 定义从这⾥才开始读 :412-416
│ └─ listeners.contextLoaded → ⑤ 监听器搬家 + ApplicationPreparedEvent :418
├─ refreshContext (⼗⼆道⼯序在此) :321
├─ listeners.started → ApplicationStartedEvent + Liveness=CORRECT :327
├─ ⑥ callRunners (live 但还没 ready) :328
└─ listeners.ready → ApplicationReadyEvent + Readiness=ACCEPTING_TRAFFIC :335

这张轴上有两个位置需要特别记住,因为绝⼤多数"扩展点没⽣效"的疑案都出在这两处:

:393 的 applyInitializers 跑在 :412-416 的 load(context, sources) 之前。 也就是说, ApplicationContextInitializer 执⾏的时候,⼀张图纸都还没

进图纸库。你在这⾥注册 BeanDefinitionRegistryPostProcessor 、往 Environment ⾥插 PropertySource、甚⾄直接往容器⾥塞图纸——全都来得及。这就是它相对@Bean 、相对 BeanFactoryPostProcessor 的全部优势。

:418 的 contextLoaded 是"离线"与"在线"的界碑。 这⼀⾏之前的事件由⼀个不属于任何容器的⼴播器发出;之后才⾛正式 multicaster。下⾯第五节会把这块讲透。

⼆、代价在 new ⾥就付掉了⼀个常被忽略的事实:三次 classpath 全盘扫描发⽣在构造器⾥,不在 run() ⾥。

public SpringApplication(@Nullable ResourceLoader resourceLoader, Class<?>... primarySources) { // :274
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "'primarySources' must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.properties.setWebApplicationType(WebApplicationType.deduce()); // :278
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class)); // :279-280
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); // :281
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); // :282
this.mainApplicationClass = deduceMainApplicationClass(); // :283
}

[boot] core/spring-boot/.../SpringApplication.java:274-284 。

new SpringApplication(App.class) 这⼀句话,背后是三趟 classLoader.getResources("META-INF/spring.factories") 加上三批反射实例化。你以为 run() 才开

始⼲活,其实 new 已经把整个 classpath 上所有 jar 的布告栏都读了⼀遍。

⽽ deduceMainApplicationClass() ( :286-296 )的实现更朴素得让⼈发笑:
private @Nullable Class<?> deduceMainApplicationClass() { // :286
return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
.walk(this::findMainClass).orElse(null);
}
private Optional<Class<?>> findMainClass(Stream<StackFrame> stack) { // :292
return stack.filter((frame) -> Objects.equals(frame.getMethodName(), "main")) // :293
.findFirst().map(StackWalker.StackFrame::getDeclaringClass);
}

Boot 判断"你的主类是谁",靠的是翻当前调⽤栈、找第⼀个⽅法名叫 main 的栈帧。不是注解,不是配置,不是构建期元数据——是站在楼梯上往下看,谁站在最下⾯那⼀级。

这个结果后⾯要⽤在 banner、启动⽇志、以及 AOT ⽣成类的命名( mainApplicationClass.getName() + "__ApplicationContextInitializer" )上。

⚠ 第⼀处暗礁,就在轴的最开头。 :313 的 listeners.starting(...) 在 :314 的 try 之外。任何监听 ApplicationStartingEvent 的代码抛异常,都不会⾛

handleRunFailure ——没有 failed 回调,没有 FailureAnalyzer 把堆栈美化成⼈话,没有 exit code 处理,就是⼀个裸的异常从 main ⾥冒出来。轴的第⼀格,同时也是防护最薄的⼀格。

三、谁去 classpath 上找⼈:本基线到底⽤哪套

这是本章最需要回源、也最容易被⽹上旧⽂章带偏的⼀节。

Boot 4 ⾥同时活着两套互不相通的发现机制。实测: find . -name "*.imports" | wc -l → 180; find . -name spring.factories | wc -l → 74(其中 src/main下 67)。不是"新的取代旧的",是分⼯。

3.1 spring.factories :没废弃,⽽且还在加新 key先把最容易写错的⼀条钉死。 SpringFactoriesLoader 在 framework 侧:

  • General purpose factory loading mechanism for internal use within the framework. // :58
  • ...
  • @since 3.2 // :90
public class SpringFactoriesLoader { // :92
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"; // :98

[framework] spring-core/src/main/java/org/springframework/core/io/support/SpringFactoriesLoader.java:58-98 。

弃⽤状态逐个核实( grep -n "Deprecated" ):

成员 坐标 @Deprecated ?

class SpringFactoriesLoader :92 否

loadFactories(Class, ClassLoader) :246 否
loadFactoryNames(Class, ClassLoader) :264 是, @Deprecated(since = "6.0") 在 :263
实例⽅法 load(...) 四个重载 :139/:156/:173/:192 否

结论:被弃⽤的只有那个"返回类名字符串列表"的静态⽅法 loadFactoryNames ,替代品是"直接给我实例"的 load(Class, ArgumentResolver, FailureHandler) 。机制本身健在。

多硬的证据算硬?看这个: org.springframework.boot.WebApplicationType$Deducer 是本基线新增的 key。

  • @since 4.0.1 // :61
public static WebApplicationType deduce() { // :63
for (Deducer deducer : SpringFactoriesLoader.forDefaultResourceLocation().load(Deducer.class)) { // :64
WebApplicationType deduced = deducer.deduceWebApplicationType();
if (deduced != null) { return deduced; }
}
return isServletApplication() ? WebApplicationType.SERVLET : WebApplicationType.NONE; // :70
}

[boot] core/spring-boot/src/main/java/org/springframework/boot/WebApplicationType.java:61-71 。

Boot 3 ⾥这段是⼀串硬编码的 ClassUtils.isPresent("org.springframework.web.servlet.DispatcherServlet", ...) 。本基线改成了 SPI: module/spring-boot-

webflux 和 module/spring-boot-webmvc 各⾃在⾃⼰的 spring.factories ⾥注册⼀个 Deducer (两处,实测),核⼼只留 jakarta.servlet.Servlet 的兜底判断( :55-56 、 :73-80 )。

注意 @since 写的是 4.0.1 ⽽不是 4.0.0 ——这是 4.0 发布之后才补的改动。如果 Spring 团队准备淘汰 spring.factories,不会在 4.0.1 往上加新 key。 这条⽐任何javadoc 措辞都有说服⼒。

另⼀条书⾯证据来⾃ EnvironmentPostProcessor ⾃⼰的 javadoc:

"EnvironmentPostProcessor implementations have to be registered in META-INF/spring.factories , using the fully qualified name of this class as the key." ——[boot] core/spring-boot/src/main/java/org/springframework/boot/EnvironmentPostProcessor.java:30-31

src/main 下 spring.factories 承载的不同 key 共 29 个(复现: find . -path '*/src/main/*' -name spring.factories -exec cat {} \; | grep -E "^[a-zA-
Z].*=" | sed 's/=.*//' | sort -u | wc -l )。这 29 个⾥有 Framework 的( org.springframework.context.ApplicationContextInitializer 、

org.springframework.core.io.ProtocolResolver )、Boot 的、还有 Spring Security 的( AbstractHttpConfigurer ),甚⾄打包⼯具链的( loader.jarmode.JarMode )。spring.factories 是⼀块跨项⽬共享的公共布告栏,谁都能往上贴,谁都能来读。

要看"往别⼈的开张流程⾥插队"到底要花多⼤成本,看 devtools 的整份注册表——全⽂ 13 ⾏:

ApplicationContext Initializers

org.springframework.context.ApplicationContextInitializer=\

org.springframework.boot.devtools.restart.RestartScopeInitializer

Application Listeners

org.springframework.context.ApplicationListener=\

org.springframework.boot.devtools.logger.DevToolsLogFactory$Listener,\org.springframework.boot.devtools.restart.RestartApplicationListener

Environment Post Processors

org.springframework.boot.EnvironmentPostProcessor=\

org.springframework.boot.devtools.env.DevToolsHomePropertiesPostProcessor,\org.springframework.boot.devtools.env.DevToolsPropertyDefaultsPostProcessor[boot] module/spring-boot-devtools/src/main/resources/META-INF/spring.factories (1 个 Initializer、2 个 Listener、2 个 EnvironmentPostProcessor)。整个devtools 那套"改⼀⾏代码⾃动重启"的把戏,接⼊点就是这 13 ⾏⽂本。

3.2 .imports :Boot ⾃⼰写的第⼆套

  • @since 2.7.0 // :43
public final class ImportCandidates implements Iterable<String> { // :45
private static final String LOCATION = "META-INF/spring/%s.imports"; // :47

[boot] core/spring-boot/src/main/java/org/springframework/boot/context/annotation/ImportCandidates.java:43-47 。

%s 填的是注解类的全限定名( String.format(LOCATION, annotation.getName()) , :84 )。所以⾃动配置的清单⽂件才叫那个⼜臭⼜⻓的名字: META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 。

⽂法简单到近乎粗暴——解析器全⻓不到三⼗⾏:

private static List<String> readCandidateConfigurations(URL url) { // :110
try (BufferedReader reader = ...) {
List<String> candidates = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) { // :115
line = stripComment(line); // :116
line = line.trim();
if (line.isEmpty()) { continue; }
candidates.add(line);
}
return candidates;
}

...

}
private static String stripComment(String line) { // :130
int commentStart = line.indexOf(COMMENT_START);
return (commentStart == -1) ? line : line.substring(0, commentStart);
}

⼀⾏⼀个全限定类名, # 起注释。没有 key,没有等号,没有逗号,没有续⾏反斜杠。多个 jar ⾥的同名⽂件由 classLoader.getResources(location) ( :103 )全量取出、逐个 addAll ( :87-90 )——⽽且不去重(对⽐ SpringFactoriesLoader 会做 toDistinctUnmodifiableList )。去重推到了下游AutoConfigurationImportSelector 的 removeDuplicates 。

3.3 反直觉的⼀条:同⼀个⽂件,两套机制并⽤这是本节最值得拍案的⼀处。打开 AutoConfigurationImportSelector :

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, // :200
@Nullable AnnotationAttributes attributes) {
ImportCandidates importCandidates = ImportCandidates.load(this.autoConfigurationAnnotation, // :202
getBeanClassLoader());
List<String> configurations = importCandidates.getCandidates(); // :204
Assert.state(!CollectionUtils.isEmpty(configurations), // :205

"No auto configuration classes found in " + "META-INF/spring/"

+ this.autoConfigurationAnnotation.getName() + ".imports. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}

...

protected List<AutoConfigurationImportFilter> getAutoConfigurationImportFilters() { // :278
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportFilter.class, this.beanClassLoader); // :279
}

...

protected List<AutoConfigurationImportListener> getAutoConfigurationImportListeners() { // :325
return SpringFactoriesLoader.loadFactories(AutoConfigurationImportListener.class, this.beanClassLoader); // :326
}

[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationImportSelector.java:200-210, 278-280, 325-327 。

第 202 ⾏读 .imports ,第 279 ⾏读 spring.factories 。同⼀个类,相隔七⼗⼏⾏。

分界线不是"新旧",是"这条⽬是不是⼀张待导⼊的图纸":

是(⼀个待导⼊的 @Configuration 类)→ .imports 。只需要⼀个名字,不需要 new 出来,不需要注⼊构造参数,不需要 @Order 排序(⾃动配置的排序另由@AutoConfigureBefore/After/Order 处理)。条⽬动辄上百条,格式越简单越好——diff 好读,⼯具好⽣成。

否(⼀个需要实例化、可能要注⼊构造参数、需要按 @Order 排序的策略对象)→ spring.factories 。它⾃带三件套: ArgumentResolver (喂构造参数)、FailureHandler (容错)、 AnnotationAwareOrderComparator.sort ( [framework] SpringFactoriesLoader.java:206 ,返回前排序)。这三件 .imports ⼀件都没有。

⽽⾃动配置的注册这⼀件事,本基线确实只⾛ .imports ,零回退。Boot 2.7 时代曾经"两边都读、读到 spring.factories ⾥的 EnableAutoConfiguration key 就打弃⽤警告",本基线连异常⽂案⾥都只提 .imports ——证据就是 :200-210 这个⽅法体本身,从头到尾只有⼀句 ImportCandidates.load 。

所以那句流传甚⼴的"spring.factories 在 Boot 4 已经废弃了",准确的说法应该是:被换掉的只有"⾃动配置类清单"这⼀个 key,不是整套机制。

3.4 清单的"⽬录"由消费⽅定,"内容"由供货⽅填.imports 也不是⾃动配置专属。全仓真正调⽤ ImportCandidates.load(...) 的有四处,其中⼀处不在 core 下:

protected List<String> loadFactoryNames() { // :100
return ImportCandidates.load(ManagementContextConfiguration.class, this.classLoader).getCandidates(); // :101
}

[boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelector.java:100-102 。

actuator ⽤同⼀套机制管理"管理端上下⽂"的配置类清单,注解换成 @ManagementContextConfiguration ,⽂件名换成 META-INF/spring/org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration.imports 。

接下来是⼀条极容易搞错、也极值得记住的结构事实:

.imports ⽂件不住在"定义那个注解的模块"⾥,⽽住在"要往那个清单⾥加东⻄的模块"⾥。

实测( find . -name "*ManagementContextConfiguration.imports" → 8 个):这个⽂件分别出现在 module/spring-boot-webmvc 、 spring-boot-webflux 、spring-boot-security 、 spring-boot-servlet 、 spring-boot-tomcat 、 spring-boot-jetty 、 spring-boot-jersey 、 spring-boot-reactor-netty ⾥。注解定义在 actuator,往清单⾥塞东⻄的是⼋个⼋竿⼦打不着的模块。

同理, org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest.imports 这个⽂件⼀份都不在 webmvc-test 模块⾥,⽽是分别住在 module/spring-boot-security-oauth2-resource-server 、 spring-boot-security-oauth2-client 、 spring-boot-security-saml2 三个 security 模块下(实测三处)。 @WebMvcTest 是谁定义的不重要,谁要往它的切⽚清单⾥投票才重要。

这正是 getResources() (多份同名⽂件全量合并)这个设计的全部价值:模块之间唯⼀的连接点是⼀个字符串⽂件名,不是编译期依赖。Boot 4 那场把上百个⾃动配置从core/spring-boot-autoconfigure 拆到 module/spring-boot-* 的⼤重组之所以做得动( wc -l 实测:core ⾥的 AutoConfiguration.imports 现在只剩 12 ⾏),这是底层前提之⼀。

3.5 还有第三种⽂法,抽屉⾥是空的META-INF/spring/ 这个⽬录⾥其实住着三种完全不同的⽂法: aot.factories (Properties,有 key 有等号有反斜杠续⾏)、 *.imports (纯⾏式),以及——

final class AutoConfigurationReplacements { // :45
private static final String LOCATION = "META-INF/spring/%s.replacements"; // :47
private static Map<String, String> readReplacements(URL url) { // :123
... Properties properties = new Properties();
properties.load(reader); // :127
}
}

[boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationReplacements.java (注意 :45 没有public )。⽤途是"⾃动配置类改名后,把 @AutoConfigureAfter(旧类) 映射到新类"。

回源核实: find . -name "*.replacements" | wc -l → 0 。机制造好了、接上了,⼀个⽂件都没有。框架给未来的⾃⼰留了⼀张搬家单,暂时还没⽤上。

⚠ 本节的批评。 .imports 的报错⽂案 :205-208 只说了⼀种可能——"如果你在⽤⾃定义打包⽅式,检查那个⽂件"。⽽实际更常⻅的失效原因是 shade / fat-jar 打包时没配

资源合并策略:因为 ImportCandidates ⽤ getResources() 合并多份,⼀旦打包⼯具⽤"后者覆盖前者"处理同名资源,你会静默丢掉⼀⼤批⾃动配置——剩下的那份⾮空,Assert.state 通过,不报错,只是少了⼀堆东⻄。这个坑⽐"⽂件完全没有"隐蔽得多,⽽报错⽂案对它只字未提。

另⼀条:spring.factories 是 classpath 全局合并的,没有作⽤域。 loadFactoriesResource ( [framework] SpringFactoriesLoader.java:329-344 )遍历所有 jar 的同名⽂件。你没法"只对某个模块启⽤某个 EnvironmentPostProcessor "——那个 jar 在 classpath 上,它就⽣效。唯⼀的开关是实现类⾃⼰在⽅法体⾥判条件(devtools 就是这么⼲的)。这是⼀种"全有或全⽆"的接⼊模型,代价直到出问题那天才会被感知到。

四、 EnvironmentPostProcessor :⼀个架在扩展点上的扩展点4.1 本基线的包路径变了,不要照抄旧⽂章

package org.springframework.boot; // :17 ←本基线:不再是 org.springframework.boot.env

...

  • @since 4.0.0 // :49

@FunctionalInterface

public interface EnvironmentPostProcessor { // :52
void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application); // :59
}

[boot] core/spring-boot/src/main/java/org/springframework/boot/EnvironmentPostProcessor.java:17-61 。

Boot 3 ⾥它是 org.springframework.boot.env.EnvironmentPostProcessor 。本基线搬到了 org.springframework.boot ,⽽且没有留兼容别名、没有 @Deprecated转发—— grep -rn "boot\.env\.EnvironmentPostProcessor" 全仓零命中(实测)。 org.springframework.boot.env 包还在,但只剩 PropertySource 相关的 12 个⽂件,⼀个 EnvironmentPostProcessor 都没有。

驱动它的那个类也搬了家,现在叫 [boot] core/spring-boot/src/main/java/org/springframework/boot/support/EnvironmentPostProcessorApplicationListener.java:65 。你从⽹上抄来的 spring.factories ⽚段如果写的是旧 FQN,在本基线上是⼀⾏不会被任何⼈读到的死⽂本——不报错,不警告,就是不⽣效。

🦴 ⻣灰级细节:⼀个⼿误,把重构的时间戳暴露了。

同⼀批搬家⾥, BootstrapContext 的 javadoc 留下了全仓唯⼀的⼀枚指纹:

  • @author Phillip Webb // BootstrapContext.java:36
  • @since 4.0.0 // :37
  • @since 2.4.0 // :38
  • @see BootstrapRegistry // :39

[boot] core/spring-boot/src/main/java/org/springframework/boot/bootstrap/BootstrapContext.java:36-39 。同⼀个 javadoc 块⾥有两个 @since 。这是"整包搬家时机械地在前⾯补了⼀⾏新 @since 、忘了删旧的"留下的痕迹。它同时说明两件事:① 这个类真实出身是 2.4.0,远早于 4.0;② 本基线⾥org.springframework.boot.bootstrap 包上那⼀⽚ @since 4.0.0 ,不代表"这些概念是 4.0 才有的",只代表"它们 4.0 才搬到这个包名下"。

(本书浅克隆、⽆ git 历史,这类判断⼀律只依据仓内可⻅痕迹,不假装查过 blame。)

4.2 它不是 SpringApplication 直接调的翻遍 SpringApplication.java 全⽂,⼀⾏ EnvironmentPostProcessor 相关逻辑都没有。真正调它的是⼀个普通的 ApplicationListener :

public class EnvironmentPostProcessorApplicationListener implements SmartApplicationListener, Ordered { // :65
public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10; // :72

...

private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) { // :130
ConfigurableEnvironment environment = event.getEnvironment();
SpringApplication application = event.getSpringApplication();
List<EnvironmentPostProcessor> postProcessors = getEnvironmentPostProcessors(
application.getResourceLoader(), event.getBootstrapContext()); // :133-134
addAotGeneratedEnvironmentPostProcessorIfNecessary(postProcessors, application); // :135
for (EnvironmentPostProcessor postProcessor : postProcessors) { // :136
postProcessor.postProcessEnvironment(environment, application); // :137
}
}

✨ 框架⽤⼀个低阶扩展点,喂养了⼀个⾼阶扩展点。 SpringApplicationRunListener 把 run ⽣命周期翻成 Spring 事件 → 事件被⼀个 ApplicationListener 收到 → 这

个 listener 再去加载并调⽤所有 EnvironmentPostProcessor 。三层,每层都是公开的扩展点,每层都可以被你⾃⼰的东⻄替换掉。

⽽"你的构造器可以声明哪些参数"这件事,被做成了运⾏时可组合的数据,⽽不是⽂档⾥的⼝头约定:

public List<EnvironmentPostProcessor> getEnvironmentPostProcessors(DeferredLogFactory logFactory,
ConfigurableBootstrapContext bootstrapContext) { // :43-44
ArgumentResolver argumentResolver = ArgumentResolver.of(DeferredLogFactory.class, logFactory); // :45
argumentResolver = argumentResolver.and(ConfigurableBootstrapContext.class, bootstrapContext); // :46
argumentResolver = argumentResolver.and(BootstrapContext.class, bootstrapContext); // :47
argumentResolver = argumentResolver.and(BootstrapRegistry.class, bootstrapContext); // :48
return this.loader.load(EnvironmentPostProcessor.class, argumentResolver); // :49
}

[boot] core/spring-boot/src/main/java/org/springframework/boot/support/SpringFactoriesEnvironmentPostProcessorsFactory.java:42-50 。

:46-48 三⾏把同⼀个 bootstrapContext 对象按三种类型各挂了⼀次——这就是接⼝ javadoc ⾥" BootstrapContext or BootstrapRegistry may also be used"那句话的物理实现。四⾏代码,换来⽤户端的写法⾃由。同⼀个 SpringFactoriesLoader 因此能同时服务"⽆参构造的 FailureAnalyzer "、"要 SpringApplication +String[] 的 RunListener"、"要 DeferredLogFactory + BootstrapContext 的 EPP"。

4.3 两层排序,两个坐标系,⼀个巧合Boot 核⼼注册了 5 个 EnvironmentPostProcessor ( [boot] core/spring-boot/src/main/resources/META-INF/spring.factories:48-53 )。它们的 order 逐个回源:

执⾏序 类 order 表达式 实际值1 RandomValuePropertySourceEnvironmentPostProcessor Ordered.HIGHEST_PRECEDENCE + 1 ( :39 ) HIGHEST+12 SystemEnvironmentPropertySourceEnvironmentPostProcessor SpringApplicationJson….DEFAULT_ORDER - 1 ( :51 ) HIGHEST+43 CloudFoundryVcapEnvironmentPostProcessor ConfigDataEnvironmentPostProcessor.ORDER - 5 ( :98 ) HIGHEST+53 SpringApplicationJsonEnvironmentPostProcessor Ordered.HIGHEST_PRECEDENCE + 5 ( :83 ) HIGHEST+55 ConfigDataEnvironmentPostProcessor Ordered.HIGHEST_PRECEDENCE + 10 ( :52 ) HIGHEST+10

⚠ 注意第 3、4 ⾏:两个数值完全相同。原因是两条推理路径在同⼀个数上撞了⻋——前者写的是"ConfigData 之前 5 格"( (MIN+10)-5 ),后者写的是"最⾼之后 5

格"( MIN+5 )。 AnnotationAwareOrderComparator.sort 是稳定排序,撞了就按 spring.factories ⾥的书写⾏号:CloudFoundry 在 :49 、SpringApplicationJson 在:52 ,于是 CloudFoundry 先跑。

这是"⽤绝对整数表达相对约束"的典型副作⽤。两个作者都在描述"我要在谁附近",却被迫落成同⼀个绝对数;最终的执⾏顺序,取决于⼀个⽂本⽂件⾥的⾏号——这不是⼀个稳定契约。

外层还有另⼀套 order,属于 ApplicationListener 之间:

组件 order 坐标EnvironmentPostProcessorApplicationListener HIGHEST+10 [boot] .../support/EnvironmentPostProcessorApplicationListener.java:72AnsiOutputApplicationListener HIGHEST+11 [boot] .../support/AnsiOutputApplicationListener.java:49-51LoggingApplicationListener HIGHEST+20 [boot] .../context/logging/LoggingApplicationListener.java:111LoggingApplicationListener 的 +20 排在 EPP listener 的 +10 之后,这个差值不是随⼿写的,是⼀条硬依赖:必须先让 ConfigData 把 application.yml ⾥的logging.level.* 读进 Environment,⽇志系统才能按配置初始化。

但这两层的数值互不相⼲。 EnvironmentPostProcessorApplicationListener 的 +10 和 ConfigDataEnvironmentPostProcessor 的 +10 是两个完全不同坐标系⾥的 10,它们相等纯属巧合(或者说,是同⼀位作者的同⼀种⼿感)。讲这块最容易讲乱,记住"外层排 listener、内层排 EPP"就不会错。

🦴 顺带⼀条设计上的漂亮解法。EPP 跑在⽇志系统初始化之前——那它想打⽇志怎么办?Boot 的答案不是"禁⽌打⽇志",⽽是发⼀张草稿纸: DeferredLogFactory 。EPP 攒

下的⽇志先记在 DeferredLogs ⾥( EnvironmentPostProcessorApplicationListener.java:74 ),等收到 ApplicationPreparedEvent 或 ApplicationFailedEvent时⼀次性 switchOverAll() 倒出来( :141-151 )。它监听失败事件也是为了这个——启动挂了的时候,你⽐任何时候都更需要那些早期⽇志。

五、 ApplicationContextInitializer :⼀处必须纠正笔记的地⽅调⽤点:

@SuppressWarnings({ "rawtypes", "unchecked" }) // :615
protected void applyInitializers(ConfigurableApplicationContext context) { // :616
for (ApplicationContextInitializer initializer : getInitializers()) { // :617
Class<?> requiredType = GenericTypeResolver.resolveTypeArgument(initializer.getClass(),
ApplicationContextInitializer.class); // :618-619
Assert.state(requiredType != null, // :620
() -> "No generic type found for initializr of type " + initializer.getClass()); // :621
Assert.state(requiredType.isInstance(context), "Unable to call initializer"); // :622
initializer.initialize(context); // :623
}
}

[boot] core/spring-boot/.../SpringApplication.java:615-625 。

先看两个花絮:

:621 的异常⽂案⾥, "initializr" 是源码⾥真实存在的拼写。少个 e ,从某个版本⼀路带到今天。活⼈痕迹。

:622 那句 "Unable to call initializer" 不带任何上下⽂——不告诉你是哪个 initializer,不告诉你期望什么类型,不告诉你实际拿到的是什么容器。这是本⽅法最不友好的⼀处报错,在⼀个"跨了三层扩展点"的启动链路⾥排查它,基本靠猜。

关于 lambda 的⼀条流传说法——本书回源后决定推翻它有⼀种说法(我的素材笔记⾥也这么写着)是:⽤ lambda 写 ApplicationContextInitializer 会在 :620 炸掉,因为 lambda 的泛型实参在字节码⾥没有签名,GenericTypeResolver 解不出来,返回 null。听起来很有道理,很多"Spring 踩坑"⽂章也这么写。

回源核实的结果是:本基线下不成⽴。

先看解析器本体:

public static @Nullable Class<?> resolveTypeArgument(Class<?> clazz, Class<?> genericType) { // :111
ResolvableType resolvableType = ResolvableType.forClass(clazz).as(genericType); // :112
if (!resolvableType.hasGenerics()) { return null; } // :113-115
return getSingleGeneric(resolvableType); // :116
}

[framework] spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java:111-117 。

关键在 ResolvableType 对类型变量的兜底:

if (this.type instanceof TypeVariable<?> variable) { // :931
if (this.variableResolver != null) { // :933
ResolvableType resolved = this.variableResolver.resolveVariable(variable);
if (resolved != null) { return resolved; }
}

// Fallback to bounds

return forType(resolveBounds(variable.getBounds()), this.variableResolver); // :940
}

[framework] spring-core/src/main/java/org/springframework/core/ResolvableType.java:931-941 。

⽽接⼝的声明是:

public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> { // :43

[framework] spring-context/src/main/java/org/springframework/context/ApplicationContextInitializer.java:43 。

C 有上界。lambda 的合成类确实拿不到实参(我实测过:lambda 的 getGenericInterfaces()[0] 是裸的 Class ,⽽匿名内部类是 ParameterizedType ),但解析失败之后并不是返回 null,⽽是 :940 回落到类型变量的上界 ConfigurableApplicationContext 。于是 :620 的断⾔通过, :622 的 isInstance(context) 对任何容器也都成⽴。

我⽤本机能找到的唯⼀⼀份 spring-core jar(6.0.15)跑了⼀次可执⾏验证——顺带说明,6.0.15 的 GenericTypeResolver.resolveTypeArgument 与本基线 7.1 快照的源码逐字相同,连⾏号都是 :111-117 ,所以结论可以外推:

lambda(泛型有上界) -> interface java.lang.CharSequence ← 拿到的是上界,⾮ null
匿名内部类 -> class java.lang.StringBuilder ← 拿到真实实参

lambda(泛型⽆上界) -> null ← 这才是会炸的情形所以准确的说法是:会炸的不是"lambda",⽽是"lambda + ⽆上界泛型"。 ApplicationContextInitializer 恰好有上界,所以 lambda 形式在本基线下能正常⼯作。⾄于:622 那条 isInstance 校验——⽤ lambda 写时它退化成了"任何 ConfigurableApplicationContext 都通过",等于校验被绕过了。真正会撞上 "Unable to callinitializer" 的,是那些⽼⽼实实写了具名类、还把泛型收窄成 AnnotationConfigServletWebServerApplicationContext 的⼈。

写源码解读书最怕的就是"听起来很对"的结论。这⼀条我按纪律回了源,写在这⾥如实呈现,也顺⼿更正掉。

🦴 另⼀个"名不副实"的⼩发现: getInitializers() 返回的是

private static <E> Set<E> asUnmodifiableOrderedSet(Collection<E> elements) { // :1478
List<E> list = new ArrayList<>(elements);
list.sort(AnnotationAwareOrderComparator.INSTANCE); // :1480
return new LinkedHashSet<>(list); // :1481
}

[boot] core/spring-boot/.../SpringApplication.java:1478-1482 。⽅法名叫 asUnmodifiableOrderedSet ,javadoc 也写着 "read-only",返回的却是⼀个普普通通的可变 LinkedHashSet ,没有 Collections.unmodifiableSet 包装。实际⽆害(每次都新建集合,改了也不影响原 List),但别照着这个名字去推断⾏为。顺带⼀提,因为每次调⽤都重排⼀遍, addInitializers(...) 只往 List 尾部追加,最终顺序仍由 @Order 决定。

六、离线⼴播器:容器还不存在,事件怎么发?

SpringApplicationRunListener 有 7 个回调,全是 default 空实现( [boot] core/spring-boot/.../SpringApplicationRunListener.java:42-111 ),实现类只重写关⼼的那⼏个。三个 @since 台阶本身就是⼀部微缩史:

starting / environmentPrepared / contextPrepared / contextLoaded :类级 1.0.0failed :2.0.0( :106 )——第⼀版竟然没有"失败"这⼀格started / ready :2.6.0( :84 、 :96 ),带 @Nullable Duration timeTaken 参数,为启动耗时可观测才加的回源核实:整个 spring-boot 仓⾥,spring.factories 注册的 SpringApplicationRunListener 只有⼀个( core/spring-boot/.../spring.factories:25-26 ),就是EventPublishingRunListener 。它甚⾄不是 public 的:

class EventPublishingRunListener implements SpringApplicationRunListener, Ordered { // :55
private final SimpleApplicationEventMulticaster initialMulticaster; // :61
EventPublishingRunListener(SpringApplication application, String[] args) { // :63
this.application = application;
this.args = args;
this.initialMulticaster = new SimpleApplicationEventMulticaster(); // :66
}

[boot] core/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java:55-67 。

✨ 这就是全章最漂亮的⼀处设计。前四个事件根本没有容器可发—— ApplicationStartingEvent 发出时, createApplicationContext() ( :318 )还差好⼏⾏才轮到。解

法是:⾃带⼀个不属于任何容器的⼴播器。 initialMulticaster 就是个裸对象,谁也不认识它,它谁也不认识,但它能⼴播。

前四个事件⾛它:

starting → multicastInitialEvent(new ApplicationStartingEvent(...)) // :75-77
environmentPrepared → multicastInitialEvent(new ApplicationEnvironmentPreparedEvent(...)) // :79-84
contextPrepared → multicastInitialEvent(new ApplicationContextInitializedEvent(...)) // :86-89

后三个⾛正式容器:

started → context.publishEvent(new ApplicationStartedEvent(...)); // :104
AvailabilityChangeEvent.publish(context, LivenessState.CORRECT) // :105
ready → context.publishEvent(new ApplicationReadyEvent(...)); // :110
AvailabilityChangeEvent.publish(context, ReadinessState.ACCEPTING_TRAFFIC) // :111
⽽界碑就是 contextLoaded ⾥的那⼀⾏ context.addApplicationListener(listener) :
public void contextLoaded(ConfigurableApplicationContext context) { // :92
for (ApplicationListener<?> listener : this.application.getListeners()) { // :93
if (listener instanceof ApplicationContextAware contextAware) { // :94
contextAware.setApplicationContext(context); // :95
}
context.addApplicationListener(listener); // :97
}
multicastInitialEvent(new ApplicationPreparedEvent(this.application, this.args, context)); // :99
}

⼀次⼲净的交接棒。把 SpringApplication 上挂的所有监听器逐个搬进正式容器;顺⼿对实现了 ApplicationContextAware 的做 setApplicationContext ——因为它们不是器,没⼈会替它们做 Aware 回调。这⾏代码之后,事件就⾛正式 multicaster 了。

还有⼀处细节值得看:

private void multicastInitialEvent(ApplicationEvent event) { // :135
refreshApplicationListeners(); // :136
this.initialMulticaster.multicastEvent(event); // :137
}
private void refreshApplicationListeners() { // :140
this.application.getListeners().forEach(this.initialMulticaster::addApplicationListener); // :141
}

每次⼴播前重新同步⼀遍名单。所以你在 starting 阶段⽤ application.addListeners(...) 加进来的监听器,下⼀个事件就能收到——名单是活的,不是启动时冻结的⼀张快照。

回到开场那个问题现在可以给出双侧证据了。 @Bean 定义的 ApplicationListener 收不到前四个事件,原因是:

Boot 侧:前四个事件由 initialMulticaster ⼴播,⽽它的名单只来⾃ application.getListeners() ( EventPublishingRunListener.java:141 )——就是

SpringApplication 上那份 List,跟容器毫⽆关系。

Framework 侧: @Bean 定义的监听器要等 refresh() ⾛到 registerListeners() 才被登记:
protected void registerListeners() { // :915
for (ApplicationListener<?> listener : getApplicationListeners()) { // :917
getApplicationEventMulticaster().addApplicationListener(listener); // :918
}
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); // :923
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); // :925
}

...

}

[framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:915-926 。这⼀⾏跑到的时候,前四个事件早发完了。

官⽅⽂档同⼝径:

"Some events are actually triggered before the ApplicationContext is created, so you cannot register a listener on those as a @Bean ." —— [boot]documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/spring-application.adoc:244

:245 与 :247-252 给出三条正解: SpringApplication.addListeners(...) 、 SpringApplicationBuilder.listeners(...) 、或者写 META-

INF/spring.factories 。

源码可推、⽂档没写的⼀条推论: @EventListener 注解形式⽐ @Bean ApplicationListener 还晚——它靠 EventListenerMethodProcessor 在 bean 实例化之后扫⽅法,早期事件更收不到。

🦴 顺带把⼀个默认值钉死(本书硬纪律:默认值⼀律回源)。Spring 事件默认同步⼴播:

public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { // :52
private @Nullable Executor taskExecutor; // :54 ←⽆初始化器

...

Executor executor = getTaskExecutor(); // :139
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null && listener.supportsAsyncExecution()) { ... }
else { invokeListener(listener, event); } // :151 ←同步调⽤
}

[framework] spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java:52-153 。字段没有初始化器,就是null ,就⾛ :151 的同步分⽀。⽂档也这么说:"Event listeners should not run potentially lengthy tasks as they execute in the same thread by default."( spring-application.adoc:278 )。在监听器⾥⼲重活,等于把启动时间挂在⾃⼰身上。

七、 ApplicationRunner 与 CommandLineRunner :差别只有⼀处,坑有好⼏处三个接⼝,都在 [boot] core/spring-boot/src/main/java/org/springframework/boot/ 下:

interface Runner { } // Runner.java:26 ←注意没有 public

// javadoc :20 "Marker interface for runners."

@FunctionalInterface

public interface ApplicationRunner extends Runner { // ApplicationRunner.java:33 @since 1.3.0 (:29)
void run(ApplicationArguments args) throws Exception; // :40
}

@FunctionalInterface

public interface CommandLineRunner extends Runner { // CommandLineRunner.java:36 @since 1.0.0 (:32)
void run(String... args) throws Exception; // :43
}

差别只有⼀个:参数类型。 CommandLineRunner 拿的是原始 String[] , ApplicationRunner 拿的是解析过的 ApplicationArguments (能问"有没有 --debug 这个选项"、"⾮选项参数有哪些")。⽂档也只讲了这⼀条差别( spring-application.adoc:331 ——顺带⼀提这⾏还有个语法笔误 "The CommandLineRunner interfacesprovides",⼜⼀处活⼈痕迹)。排序⽅式两者完全⼀致: Ordered 或 @Order ,两个接⼝的 javadoc :26 写的是同⼀句话。

@since 说明了顺序: CommandLineRunner 是 1.0.0 就有的原⽣货, ApplicationRunner 是 1.3.0 补的——先有"给我原始参数",后来才有⼈说"我不想⾃⼰解析"。

🦴 Runner 这个 package-private 标记接⼝,是全章我最喜欢的⼀个设计。它存在的唯⼀理由是让驱动代码能⼀次性查两种 runner:

private void callRunners(ConfigurableApplicationContext context, ApplicationArguments args) { // :767
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
String[] beanNames = beanFactory.getBeanNamesForType(Runner.class); // :769
Map<Runner, String> instancesToBeanNames = new IdentityHashMap<>(); // :770
for (String beanName : beanNames) {
instancesToBeanNames.put(beanFactory.getBean(beanName, Runner.class), beanName); // :772
}
Comparator<Object> comparator = getOrderComparator(beanFactory)
.withSourceProvider(new FactoryAwareOrderSourceProvider(beanFactory, instancesToBeanNames)); // :774-775
instancesToBeanNames.keySet().stream().sorted(comparator).forEach((runner) -> callRunner(runner, args)); // :776
}
private void callRunner(Runner runner, ApplicationArguments args) { // :786
if (runner instanceof ApplicationRunner) { // :787
callRunner(ApplicationRunner.class, runner, (applicationRunner) -> applicationRunner.run(args));
}
if (runner instanceof CommandLineRunner) { // :790 ←不是 else if
callRunner(CommandLineRunner.class, runner,
(commandLineRunner) -> commandLineRunner.run(args.getSourceArgs()));
}
}

[boot] core/spring-boot/.../SpringApplication.java:767-794 。

同时不 public,等于顺⼿挡住了"⽤户直接实现 Runner "这条路——⼀个纯粹为内部查询⽽⽣、⼜刻意不对外开放的类型。这种克制在⼀个到处是 public 接⼝的框架⾥,反⽽显眼。

四条可考据的⾏为:

  1. ⚠ ⼀个 bean 同时实现两个接⼝,会被调⽤两次。 :787 与 :790 是两个独⽴的 if ,不是 else if 。先 ApplicationRunner (拿 ApplicationArguments ),后CommandLineRunner (拿 String[] )。这不是理论上的坑,是"我为了兼容两种写法就都实现了"之后真会中的招。
  1. ⚠ 所有 runner bean 在第⼀个 runner 执⾏之前就已经全部实例化完毕。 :771-773 的循环与 :776 的 forEach 是两趟。想靠"排在后⾯的 runner 晚⼀点才被创建"来做延迟初始化,⾏不通。
  1. 排序看的是 bean 的"定义源",不只是类。 FactoryAwareOrderSourceProvider ( 同⽂件:1843-1874 )取合并后 RootBeanDefinition 的
getResolvedFactoryMethod() 与 getTargetType() 当 order source,所以 @Bean @Order(1) CommandLineRunner foo() {...} ——注解打在⼯⼚⽅法上——

是⽣效的。但它 catch 了 NoSuchBeanDefinitionException 返回 null:⽤ registerSingleton ⼿⼯塞进去的 runner 没有图纸,排序时会退化成"没有 ordersource"。

4. ⚠ runner 抛异常 = 应⽤启动失败。异常被包成 IllegalStateException("Failed to execute ApplicationRunner") ( :798-799 ),⽽ callRunners 在
run() 的 try 块内( :328 ),于是⾛ handleRunFailure → listeners.failed → reportFailure → context.close() ( :810-820 )。在 runner ⾥写"顺⼿

预热⼀下缓存",缓存服务没起来,整个应⽤就起不来。

时序上,runner 卡在⼀个很微妙的位置: listeners.started(...) ( :327 )→ callRunners ( :328 )→ listeners.ready(...) ( :335 )。也就是说,runner 执⾏

期间,应⽤是 live( LivenessState.CORRECT 已发)但还没 ready( ACCEPTING_TRAFFIC 未发)。⽂档把这个中间态说得很明⽩( spring-application.adoc:210 ),并给了⼀条 TIP:

"Tasks expected to run during startup should be executed by CommandLineRunner and ApplicationRunner components instead of using Spring componentlifecycle callbacks such as @PostConstruct ." —— spring-application.adoc:214别在 @PostConstruct ⾥⼲启动任务,这是官⽅原话。理由也很直接: @PostConstruct 跑在单个器的成形过程中,那时候整座坊还没装完;runner 跑在容器完全就绪之后。

🦴 ⻣灰级细节

⼀、 SpringApplicationRunListeners 只保护 failed ⼀条路。

private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction,
@Nullable Consumer<StartupStep> stepAction) { // :120
StartupStep step = this.applicationStartup.start(stepName); // :122
this.listeners.forEach(listenerAction); // :123 ←裸的 forEach
if (stepAction != null) { stepAction.accept(step); }
step.end(); // :127
}

[boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java:120-128 。

七个转发⽅法⾥,只有 failed ⾛ callFailedListener ( :96-114 )被 try/catch 包着;其余六个都是 :123 那⼀⾏裸的 forEach 。任何监听器抛异常都会直接打断启

动。⽽且 callFailedListener ⾥还有⼀处克制得体的判断: exception == null 时会 ReflectionUtils.rethrowRuntimeException(ex) 直接抛( :102-104 )——只

有"确实存在原始异常"时才把监听器⾃身的异常降级成 warn ⽇志,绝不拿"处理失败的失败"去盖掉真正的失败。

顺带⼀处⼩瑕疵: step.end() ( :127 )不在 finally ⾥。监听器抛异常时这个 StartupStep 不会被 end, BufferingApplicationStartup ⾥会留下⼀个永远结束不了的步骤。

⼆、构造时 List.copyOf(listeners) ( 同⽂件:51 )——不可变快照。 run() 跑到⼀半再往 SpringApplication 上加 RunListener 是没⽤的(但加ApplicationListener 有⽤,⻅第六节的 refreshApplicationListeners )。

三、七个稳定的 ApplicationStartup 步骤名: spring.boot.application.starting / .environment-prepared / .context-prepared / .context-loaded /.started / .ready / .failed ( :56 – :86 )。这些字符串是可以直接拿去配 BufferingApplicationStartup 过滤器的。

四、 configureHeadlessProperty 的体贴。

System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,
System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless))); // :449-450

先⽤带默认值的 getProperty 读⼀次再写回去——你要是已经⼿⼯设过 java.awt.headless ,Boot 不会覆盖你。⼀⾏代码⾥的两次系统属性访问,就是为了这个。

五、 spring.main.environment-prefix 不许写在配置⽂件⾥。

Assert.state(!environment.containsProperty("spring.main.environment-prefix"), // :359