源码小说CodeStory
登录
上一章

44,060 字 · 约 110 分钟

下一章
字体

主题

版式

第36章 卷十一 · 一句话开张 · 一句话开张:SpringApplication.run

卷⼗⼀ · ⼀句话开张⼀句话开张:SpringApplication.run「我不是⼀间更好的总装房。 我只是站在总装房⻔⼝的那个⼈——负责在开⼯前把料备⻬、把图纸摆好、把该通知的⼈通知到; 开⼯之后再把成品送到该去的岗位上,顺⼿在⻔⼝拴⼀根绳,防着哪天要收摊。 ⾄于⾥⾯那⼗⼆道⼯序——我⼀道也没碰过。」 —— SpringApplication.run() 的⾃⽩⼀、两个"⼀句话",差在哪先把两句话并排放着看。

裸 Framework 的启动,⼀句话:

// [framework] spring-context/src/main/java/org/springframework/context/annotation/AnnotationConfigApplicationContext.java:89

public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this(); // :90
register(componentClasses); // :91
refresh(); // :92
}

三⾏。就这些。 建⼀个空总装房、把图纸塞进去、开⼯。没有 Environment 编排、没有 banner、没有事件、没有 Runner、没有关机绳、没有失败诊断、没有退出码——⼀件都没有。

Boot 的启动,也是⼀句话:

SpringApplication.run(MyApp.class, args);

于是有了本章要回答的唯⼀问题:这两句话之间,到底隔着什么?

⼀个流传很⼴的错误答案是"Boot 优化了容器"。这是错的,⽽且错得很有代表性。 我把两边的 refresh() 逐⾏⽐对过:Boot 对它的全部贡献,是下⾯这个⽅法——// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:755

protected void refresh(ConfigurableApplicationContext applicationContext) {
applicationContext.refresh();
}

⼀⾏。调了⼀下。 ⼗⼆道⼯序(ch15)Boot ⼀道没动、⼀个字没改。

那 Boot 到底加了什么?加的东⻄全在容器外⾯: refresh() 之前把参数备⻬, refresh() 之后把⼈送到岗,两侧各拴⼀根安全绳。⽤坊⾥的话说:成器坊还是那座成器坊,Boot 只是把"开⼯前你本来要⾃⼰跑的那⼆⼗⼏趟腿"变成了⼀张印好的检查单。

这⼀章就沿着这张检查单⾛⼀遍。

⼆、把整张检查单摊在桌上唯⼀权威在 [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:304-342 。三⼗九⾏,我⼀⾏不删地抄下来——因为这三⼗九⾏的每⼀⾏位置都有讲究,后⾯⼏乎所有⽞学问题都能在这张图上定位:

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

public ConfigurableApplicationContext run(String... args) {
Startup startup = Startup.create(); // :305秒表(可能是 CRaC版)
if (this.properties.isRegisterShutdownHook()) { // :306
SpringApplication.shutdownHook.enableShutdownHookAddition(); // :307允许挂关机绳
}
DefaultBootstrapContext bootstrapContext = createBootstrapContext(); // :309临时储物柜
ConfigurableApplicationContext context = null; // :310
configureHeadlessProperty(); // :311
SpringApplicationRunListeners listeners = getRunListeners(args); // :312
listeners.starting(bootstrapContext, this.mainApplicationClass); // :313⚠ 在 try之外
try { // :314
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); // :315
ConfigurableEnvironment environment =
prepareEnvironment(listeners, bootstrapContext, applicationArguments); // :316 ←拼账本
Banner printedBanner = printBanner(environment); // :317
context = createApplicationContext(); // :318 ←造总装房
context.setApplicationStartup(this.applicationStartup); // :319
prepareContext(bootstrapContext, context, environment,
listeners, applicationArguments, printedBanner); // :320 ←点⽕前装配
refreshContext(context); // :321★ 交棒给 Framework
afterRefresh(context, applicationArguments); // :322 ←空⽅法
Duration timeTakenToStarted = startup.started(); // :323
if (this.properties.isLogStartupInfo()) { // :324
new StartupInfoLogger(this.mainApplicationClass, environment)
.logStarted(getApplicationLog(), startup); // :325
}
listeners.started(context, timeTakenToStarted); // :327
callRunners(context, applicationArguments); // :328
}
catch (Throwable ex) {
throw handleRunFailure(context, ex, listeners); // :331
}
try {
if (context.isRunning()) { // :334⚠ 守卫
listeners.ready(context, startup.ready()); // :335
}
}
catch (Throwable ex) {
throw handleRunFailure(context, ex, null); // :339⚠ 第三参是 null
}
return context; // :341
}

四段结构⼀⽬了然:

段 ⾏ ⼲什么 谁在⼲⻜前 :305 – :320 推断我是什么应⽤、把 Environment 拼好、把容器造出来但不点⽕ 全是 Boot ⾃⼰的代码

点⽕ :321 context.refresh() 纯 Framework,Boot 只是调了⼀下

落地 :322 – :328 计时、发 started、跑 Runner 全是 Boot ⾃⼰的代码安全绳 :307 、 :331 、 :339 失败时关容器+算退出码+出诊断报告;正常时挂 JVM 关机钩⼦ 全是 Boot ⾃⼰的代码标了三个 ⚠ ,先记下,后⾯⼀个个还。

三、run 还没开始,classpath 已经被扫过三遍很多⼈以为 run() 是起点。不是。 起点在 new SpringApplication(...) ⾥,⽽那时该定的已经定了⼀半:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:274

public SpringApplication(@Nullable ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader; // :275
Assert.notNull(primarySources, "'primarySources' must not be null"); // :276
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); // :277
this.properties.setWebApplicationType(WebApplicationType.deduce()); // :278 ←我是什么应⽤
this.bootstrapRegistryInitializers = new ArrayList<>(
getSpringFactoriesInstances(BootstrapRegistryInitializer.class)); // :279 ←扫第 1遍
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); // :281扫第 2遍
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); // :282扫第 3遍
this.mainApplicationClass = deduceMainApplicationClass(); // :283 ←我是谁
}
三次 getSpringFactoriesInstances ,底下都是同⼀句 SpringFactoriesLoader.forDefaultResourceLocation(getClassLoader()).load(...) ( :472 ),读的是所有 jar

⾥的 META-INF/spring.factories 。换句话说:你在 main ⽅法⾥写的第⼀个 new ,已经把整条 classpath 的 spring.factories 翻了⼀遍。

core 模块⾃⼰贡献的数量少得让⼈意外( [boot] core/spring-boot/src/main/resources/META-INF/spring.factories ): ApplicationContextInitializer 只有三个
( :34-36 ), ApplicationListener 只有六个( :40-45 ), SpringApplicationRunListener 只有⼀个( :26 )。⽽ BootstrapRegistryInitializer 在这个⽂件⾥⼀条都没有

——默认那个列表是空的。

3.1 「我是谁」:StackWalker 顺着栈往回摸// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:286

private @Nullable Class<?> deduceMainApplicationClass() {
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);
}

判据只有⼀条:栈上第⼀个⽅法名叫 main 的帧,它所在的类就是"主类"。

本基线如此:这⾥⽤的是 java.lang.StackWalker 。⽹上⼤量关于 Boot 2/3 的⽂章写的是 new RuntimeException().getStackTrace() ——那是更早的写法,本仓已不是。

坑也就在这⼀条判据上:如果你不在 main ⾥ new 它(测试⾥、静态初始化块⾥、别的线程⾥), mainApplicationClass 就是 null 。 字段本身标着 @Nullable ( :213 ),下游

到处判空:⽇志退回 SpringApplication.class 的 logger( :671-676 );启动⽇志会打成 Starting application using Java ... ——那句没有类名的启动⽇志,不是 bug,就
是这条路径⾛上了。⽽在 AOT 模式下它不许为 null,直接 Assert.state(this.mainApplicationClass != null, "No application main class found") ( :426 )。

3.2 「我是什么应⽤」:本章最反旧版记忆的⼀处

WebApplicationType 三个值: NONE / SERVLET / REACTIVE ( [boot] core/spring-
boot/src/main/java/org/springframework/boot/WebApplicationType.java:41 、 :47 、 :53 ,类级 @since 2.0.0 )。这三个值⼆⼗年不变。变的是怎么推断出来:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/WebApplicationType.java:63

public static WebApplicationType deduce() {
for (Deducer deducer : SpringFactoriesLoader.forDefaultResourceLocation().load(Deducer.class)) {
WebApplicationType deduced = deducer.deduceWebApplicationType();
if (deduced != null) {
return deduced; // :67
}
}
return isServletApplication() ? WebApplicationType.SERVLET : WebApplicationType.NONE; // :70
}

这是本基线与 Boot 3 通⾏说法差异最⼤的⼀处,务必标"本基线如此"。

Boot 3 时代的写法是 deduceFromClasspath() ,包私有,内部⼀串硬编码 if ,直接在 core ⾥写 DispatcherServlet / DispatcherHandler / Jersey 的类名字符

串。

本基线不是这样: deduce() 是 public static ,javadoc 上明写 @since 4.0.1 ( :61 ),它先⾛ SpringFactoriesLoader 加载⼀个新的公开 SPI
WebApplicationType.Deducer (接⼝在 :106 , @FunctionalInterface ,同样 @since 4.0.1 ),全部 Deducer 都返回 null 才回落到本地兜底。

⽽两个真正的判定者,搬到 module ⾥去了:

// [boot] module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/WebMvcWebApplicationTypeDeducer.java:34

@Order(10) // Ordered before WebFlux
class WebMvcWebApplicationTypeDeducer implements WebApplicationType.Deducer {
private static final String[] INDICATOR_CLASSES = { "jakarta.servlet.Servlet",

"org.springframework.web.servlet.DispatcherServlet",

"org.springframework.web.context.ConfigurableWebApplicationContext" }; // :37-39

@Override

public @Nullable WebApplicationType deduceWebApplicationType() {

// Guard in case the classic module is being used and dependencies are excluded

for (String indicatorClass : INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(indicatorClass, null)) {

return null; //缺⼀个就让位

}
}
return WebApplicationType.SERVLET;
}
}
WebFlux 那个是对偶写法, @Order(20) // Ordered after MVC ,认 reactor.core.publisher.Mono 与 org.springframework.web.reactive.DispatcherHandler 两个
类( [boot] module/spring-boot-webflux/src/main/java/org/springframework/boot/webflux/WebFluxWebApplicationTypeDeducer.java:34 、 :37-38 )。

净语义与 Boot 3 ⼀样(MVC 优先于 WebFlux),但机制彻底换了:从"core ⾥⼀串硬编码 if"变成"按 @Order 排队的可插拔 SPI"。

为什么⾮改不可?第⼀性上只有⼀条理由:Boot 4 的模块化把依赖⽅向掰过来了。 core 不能再 import (哪怕只是字符串地提及)webmvc/webflux 的类名——判定权必须交回给拥有那些类的模块。这是⼀次被架构逼出来的重构,⽽不是为了好看。

完整链路(回源核实):

1. webmvc 模块在 + 三个指示类⻬ → SERVLET (Order 10 先⼿)
  1. 否则 webflux 模块在 + 两个类⻬ → REACTIVE
3. 否则本地兜底 isServletApplication() ——只认 jakarta.servlet.Servlet 与 ConfigurableWebApplicationContext 两个( :55-56 ,注意这⾥没有
DispatcherServlet )→ SERVLET
  1. 否则 NONE

⚠ 第 3 步是个反直觉的坑:你只是为了某个⼯具类引了 jakarta.servlet ,⼜恰好 classpath 上有 spring-web ,压根没打算起 web 容器——它照样把你判成 SERVLET。这时

候唯⼀的解药是 spring.main.web-application-type=none (配置元数据在 [boot] core/spring-boot/src/main/resources/META-INF/additional-spring-
configuration-metadata.json:614-619 ,描述原⽂ If not set, auto-detected based on the classpath ,故意没写 defaultValue)。

四、临时储物柜:BootstrapContext:309 那⼀⾏造了个东⻄,它的⽣命只有半个 run() ⻓:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:344

private DefaultBootstrapContext createBootstrapContext() {
DefaultBootstrapContext bootstrapContext = new DefaultBootstrapContext();
this.bootstrapRegistryInitializers.forEach((i) -> i.initialize(bootstrapContext));
return bootstrapContext;
}

它解决的第⼀性问题只有⼀句话:从 run() 开始到 prepareContext 结束这段时间⾥, ApplicationContext 还不存在——谁来当单例缓存?

典型场景是 Spring Cloud Config / Vault 这类:在 EnvironmentPostProcessor 阶段(还没有容器)就要去远端拉配置,总不能每读⼀个配置就 new ⼀个 HTTP 客户端;可那时候没有容器,注册不成 bean。 BootstrapContext 就是这段真空期的"DI 容器替身"。

它的数据结构朴素到近乎寒酸:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/bootstrap/DefaultBootstrapContext.java:38

public class DefaultBootstrapContext implements ConfigurableBootstrapContext {
private final Map<Class<?>, InstanceSupplier<?>> instanceSuppliers = new HashMap<>(); // :40
private final Map<Class<?>, Object> instances = new HashMap<>(); // :42
private final ApplicationEventMulticaster events = new SimpleApplicationEventMulticaster(); // :44
}

key 是 Class<?> ——⼀个类型只能存⼀个实例,没有 bean name 这回事。 这是它与真容器最⼤的差别,也是它的边界:想放两个同类型对象,做不到。

最妙的是它的死法。 prepareContext 中段调 bootstrapContext.close(context) ( :395 ),但这个 close 什么都不销毁——它只⼴播⼀个BootstrapContextClosedEvent ,让登记过 addCloseListener 的⼈有机会把⾃⼰搬进真正的容器。 BootstrapRegistry 的 javadoc 把这个意图写得很直⽩:"For example,an instance may choose to register itself as a regular Spring bean so that it is available for the application to use."

⽤坊⾥的话说:⾐帽间还没开⻔的时候,贵重物品先寄存在⻔⼝的柜⼦⾥;⾐帽间⼀开⻔,柜⼦⼴播⼀声"我要撤了,东⻄⾃⼰领⾛",登记过的⼈各⾃把东⻄搬进去。

🦴 ⼀处只有读源码才看得到的搬家痕迹。 [boot] core/spring-boot/src/main/java/org/springframework/boot/bootstrap/BootstrapContext.java:37-38 的同

⼀段 javadoc ⾥,并排写着两个 @since : java * @since 4.0.0 * @since 2.4.0 标准 javadoc ⾥ @since 不该出现两次。这两⾏合起来说的是:接⼝本身 2.4 就有了,但"它在 org.springframework.boot.bootstrap 这个包⾥"这件事是 4.0 才成⽴的——Boot 3 时代它在 org.springframework.boot 根包。同⼀种痕迹在

AnsiOutputApplicationListener (现在的坐标是 [boot] core/spring-
boot/src/main/java/org/springframework/boot/support/AnsiOutputApplicationListener.java:34 ,标 @since 4.0.0 )身上也有——那个类显然远早于 4.0。

这也是我要批评的⼀处:⽤重复的 @since 表达"类还是⽼类、坐标是新坐标",是个聪明但不规范的偷懒。对读源码的⼈是线索,对靠 javadoc ⽣成的⽂档和靠 @since 做兼容判断的⼯具,就是噪⾳。(说明:这是我在仓库内可⻅的标注,本书浅克隆⽆ git 历史,不据此推断任何提交时间。)

五、两个⼴播站:为什么你的 @EventListener 收不到早期事件:312 那⾏ getRunListeners(args) 造出来的,是 run ⽅法⾃⼰的⼀条事件总线——它和容器⾥那套 ApplicationEventMulticaster 不是同⼀个东⻄。这是本章最值得单独讲清楚的⼀处接缝。

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:453

private SpringApplicationRunListeners getRunListeners(String[] args) {
ArgumentResolver argumentResolver = ArgumentResolver.of(SpringApplication.class, this);
argumentResolver = argumentResolver.and(String[].class, args);
List<SpringApplicationRunListener> listeners =
getSpringFactoriesInstances(SpringApplicationRunListener.class, argumentResolver); // :456
SpringApplicationHook hook = applicationHook.get(); // :458 ←后⾯第⼗⼀节要⽤
SpringApplicationRunListener hookListener = (hook != null) ? hook.getRunListener(this) : null;
if (hookListener != null) {
listeners = new ArrayList<>(listeners);
listeners.add(hookListener);
}
return new SpringApplicationRunListeners(logger, listeners, this.applicationStartup);
}

⽽ spring.factories ⾥注册的 SpringApplicationRunListener 本基线只有⼀个: EventPublishingRunListener 。它是全篇最精妙的⼀个类,因为它同时脚踏两条船:

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

class EventPublishingRunListener implements SpringApplicationRunListener, Ordered {
private final SimpleApplicationEventMulticaster initialMulticaster; // :61 ←⾃带的对讲机

@Override

public void starting(ConfigurableBootstrapContext bootstrapContext) { // :75
multicastInitialEvent(new ApplicationStartingEvent(...)); //对讲机
}

@Override

public void contextLoaded(ConfigurableApplicationContext context) { // :92
for (ApplicationListener<?> listener : this.application.getListeners()) {
if (listener instanceof ApplicationContextAware contextAware) {
contextAware.setApplicationContext(context); // :95
}
context.addApplicationListener(listener); // :97★ 交接班就在这⼀⾏
}
multicastInitialEvent(new ApplicationPreparedEvent(...)); // :99还是对讲机
}

@Override

public void started(ConfigurableApplicationContext context, @Nullable Duration timeTaken) {
context.publishEvent(new ApplicationStartedEvent(...)); // :104★ 换成⼤楼⼴播
AvailabilityChangeEvent.publish(context, LivenessState.CORRECT); // :105
}

@Override

public void ready(ConfigurableApplicationContext context, @Nullable Duration timeTaken) {
context.publishEvent(new ApplicationReadyEvent(...)); // :110⼤楼⼴播
AvailabilityChangeEvent.publish(context, ReadinessState.ACCEPTING_TRAFFIC); // :111
}
}

看清楚了:

refresh 之前的四个事件( starting / environmentPrepared / contextPrepared / contextLoaded )⾛ multicastInitialEvent ( :135-138 ),⽤它⾃⼰带的那个

multicaster。为什么必须⾃⼰带?因为容器⾥的 multicaster 要到 refresh() 的第 8 道⼯序 initApplicationEventMulticaster() 才存在——在那之前,容器没有⼴播能⼒。

refresh 之后的两个事件( started / ready )⾛ context.publishEvent(...) ,⽤容器的 multicaster。
✨ 这就是"为什么我写了 @EventListener(ApplicationStartingEvent.class) ,它永远不触发"的根因。 @EventListener 是靠 EventListenerMethodProcessor

在 refresh 期间从 bean 上扫出来的。⽽ ApplicationStartingEvent 是在容器还不存在时⽤对讲机喊的——对讲机⾥喊的话,只有当时在场的⼈听得⻅。要收早期事件只

有两条路:在 spring.factories ⾥注册 ApplicationListener ,或者 SpringApplication.addListeners(...) 。
交接班的确切时刻,是 contextLoaded ⾥的 context.addApplicationListener(listener) ( :97 )——SpringApplication 上挂的 listener 与容器 listener,这⼀⾏合

流。合流之后紧接着发的 ApplicationPreparedEvent 仍然⾛对讲机( :99 ),因为此刻容器还没 refresh。

还有两处⼯程上的细致活,值得记:

每次⼴播前都先 refreshApplicationListeners() ( :140-142 )把 application.getListeners() 重新灌⼀遍——因为⽤户完全可能在上⼀个事件的回调⾥⼜

addListeners() 。
failed 有个 fallback( :114-133 ):容器如果不是 active,就把 context 上已注册的 listener 全搬进 initialMulticaster ,装上 LoggingErrorHandler 再⼴播——保

证"容器炸得太早,失败事件也送得出去"。

七个回调对应七个时刻,并且全是接⼝上的 default 空⽅法( [boot] core/spring-

boot/src/main/java/org/springframework/boot/SpringApplicationRunListener.java ),所以实现类可以只关⼼其中⼀格。它们的 @since 连起来是⼀条⼗年的年

轮: ApplicationEnvironmentPreparedEvent 1.0.0、 ApplicationFailedEvent 1.0.0、 ApplicationReadyEvent 1.3.0、 ApplicationStartingEvent 1.5.0、ApplicationStartedEvent 2.0.0、 ApplicationContextInitializedEvent 2.1.0——七个事件不是⼀次设计出来的,是⼀格⼀格补⻬的。

⚠ ⽽包装层 SpringApplicationRunListeners 的 doWithListeners ( [boot] core/spring-
boot/src/main/java/org/springframework/boot/SpringApplicationRunListeners.java:120-128 )只有⼀⾏ this.listeners.forEach(listenerAction) ,没有任何

try/catch。也就是说:除 failed 之外的任何⼀个回调,只要有⼀个 listener 抛异常,整个 run 就炸。 唯独 failed 被特殊保护( :96-114 ),listener 在处理失败通知时再抛异常也只 warn ⼀⾏ "Error handling failed (...)" ——失败处理链路⾃⼰不能再制造失败,这条设计是对的。

六、prepareEnvironment:先猜⼀个,读完配置发现猜错就整体搬家:316 这⼀步是整条流⽔线信息密度最⾼的地⽅。⼗⼏⾏,每⾏都是⼀个决定:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:350

private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
ConfigurableEnvironment environment = getOrCreateEnvironment(); // :353先猜⼀个
configureEnvironment(environment, applicationArguments.getSourceArgs()); // :354
ConfigurationPropertySources.attach(environment); // :355第⼀次挂
listeners.environmentPrepared(bootstrapContext, environment); // :356★ 全流程最⼤的⿊箱
ApplicationInfoPropertySource.moveToEnd(environment); // :357
DefaultPropertiesPropertySource.moveToEnd(environment); // :358
Assert.state(!environment.containsProperty("spring.main.environment-prefix"),
"Environment prefix cannot be set via properties."); // :359
bindToSpringApplication(environment); // :361★ spring.main.*落地
if (!this.isCustomEnvironment) { // :362
EnvironmentConverter environmentConverter = new EnvironmentConverter(getClassLoader());
environment = environmentConverter.convertEnvironmentIfNecessary(
environment, deduceEnvironmentClass()); // :364★ 换壳
}
ConfigurationPropertySources.attach(environment); // :366第⼆次挂
return environment;
}

6.1 :356 这⼀⾏背后, application.yml 才被读进来这⼀⾏发出 ApplicationEnvironmentPreparedEvent ,被 EnvironmentPostProcessorApplicationListener 接住,遍历所有 EnvironmentPostProcessor 。⽽

ConfigDataEnvironmentPostProcessor ( [boot] core/spring-
boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessor.java:52 , ORDER = HIGHEST_PRECEDENCE + 10 )就在这⾥把

application.yml 、profile、 spring.config.import 全部处理完。

顺带解开⼀个⽇常疑问:为什么 logging.level.* 能写在 application.yml ⾥、并且真的⽣效? 因为 LoggingApplicationListener 的 DEFAULT_ORDER =
HIGHEST_PRECEDENCE + 20 ( [boot] core/spring-boot/src/main/java/org/springframework/boot/context/logging/LoggingApplicationListener.java:111 )——

+10 严格早于 +20,配置⽂件先被读进来,⽇志系统后初始化。 ⼀个数字之差,⼀整条因果链。

(配置⽂件的加载顺序与优先级归 ch43,这⾥只钉它在时间轴上的这⼀格: :356 这⼀⾏之前, application.yml ⾥的字⼀个也没进 Environment。)

6.2 Boot 与 Framework 在 profile 上的分家点

getOrCreateEnvironment() ( :475-485 )按 WebApplicationType 造出三种 Environment 之⼀。三个类共⽤同⼀组 override,⽽其中两个是 return null :

// [boot] core/spring-boot/src/main/java/org/springframework/boot/ApplicationEnvironment.java:31

class ApplicationEnvironment extends StandardEnvironment {

@Override

protected @Nullable String doGetActiveProfilesProperty() { return null; } // :33-36

@Override

protected @Nullable String doGetDefaultProfilesProperty() { return null; } // :38-41

@Override

protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources ps) {
return ConfigurationPropertySources.createPropertyResolver(ps); // :43-46
}
}

⽽ Framework 那边的默认实现是直接去读: [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:290-291 返回

getProperty(ACTIVE_PROFILES_PROPERTY_NAME) ,常量就是 "spring.profiles.active" ( :77 )。

Boot 把这条腿掐断了。 为什么?因为如果不掐, spring.profiles.active 会被读两次——Environment 层⼀次、ConfigData 层⼀次,⽽这两处对"profile 组""profile 之间的import 顺序"的理解并不相同,语义会打架。掐断是为了让 profile 只有⼀个权威解释者。

呼应这个决定的,是 configureProfiles 这个⽅法:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:543

protected void configureProfiles(ConfigurableEnvironment environment, String[] args) {
}

⽅法体是空的。 javadoc ⾃⼰解释了:"Additional profiles may be activated during configuration file processing through the spring.profiles.activeproperty." 它只是给⼦类留的 override 点。⼀个空⽅法,把整块职责让了出去。

6.3 命令⾏参数为什么是最⾼优先级// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:513

protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) {
MutablePropertySources sources = environment.getPropertySources();
if (!CollectionUtils.isEmpty(this.defaultProperties)) {
DefaultPropertiesPropertySource.addOrMerge(this.defaultProperties, sources); // :516
}
if (this.addCommandLineProperties && args.length > 0) {
String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
PropertySource<?> source = sources.get(name);
if (source != null) { //已有同名 →包成 Composite,新的在前
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(
new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args)); // :524
composite.addPropertySource(source);
sources.replace(name, composite);
}
else {
sources.addFirst(new SimpleCommandLinePropertySource(args)); // :529★ addFirst
}
}
environment.getPropertySources().addLast(new ApplicationInfoPropertySource(this.mainApplicationClass)); // :532
}
addFirst ——⼀⾏代码回答了"为什么 --server.port=9000 能压过 application.yml "。⽽末尾那个 addLast 的 ApplicationInfoPropertySource 只提供两个
key( spring.application.version 与 spring.application.pid ),它就是启动⽇志⾥那个 PID 和版本号的来源。

6.4 "我需要读配置才知道该造什么 Environment,但读配置需要 Environment"

这是⼀个漂亮的⾃举困局。 getOrCreateEnvironment() 在最开头就造好了 Environment,可那时候 spring.main.web-application-type 还没被 bind(要等 :361 )。如果⽤
户在 application.yml ⾥写了 spring.main.web-application-type=none ,前⾯按 SERVLET 造出来的 ApplicationServletEnvironment 就是错的。

解法极其朴素:先按猜的型号造⼀个;bind 完之后重新算⼀遍该是什么类型;不符就整体搬家。 这就是 :364 的 convertEnvironmentIfNecessary ——新建⼀个正确类型的

Environment,把 activeProfiles、conversionService、所有 PropertySource ⼀件件搬过去,顺⼿剔掉 servlet 专属的那三个 source( SERVLET_CONTEXT / SERVLET_CONFIG /

JNDI )。搬完之后 :366 必须再 attach ⼀次——因为整个 Environment 实例已经换了个⼈,第⼀次挂的那个"元 PropertySource"跟着旧实例⾛了。

⚠ 两个暗礁,都在这⼀步:

  1. 换壳只在 !this.isCustomEnvironment 时做( :362 )。你只要调过 setEnvironment(...) ,这个标志就是 true,Boot 从此再也不敢帮你换。⾃⼰设了 Environment ⼜改 web 类型,类型对不上是你⾃⼰的事。
2. EnvironmentConverter 内部⽤反射 getDeclaredConstructor() 造新实例,失败就静默退回 new ApplicationEnvironment() ,⼀⾏⽇志都没有( [boot]
core/spring-boot/src/main/java/org/springframework/boot/EnvironmentConverter.java 的 createEnvironment ⼀段)。这是我在本章要点的第⼆处名:静默

降级是排障者的敌⼈,这⾥⾄少值得⼀句 debug ⽇志。

6.5 ⼀条⾃⼰保护⾃⼰的断⾔

Assert.state(!environment.containsProperty("spring.main.environment-prefix"),
"Environment prefix cannot be set via properties."); // :359-360

这是个先有鸡还是先有蛋的闭环:环境变量前缀决定了怎么读环境变量,如果它⾃⼰也从配置⾥读,逻辑就咬住⾃⼰的尾巴。 所以 Boot 直接堵死:只能⽤ setEnvironmentPrefix()

在代码⾥设。宁可启动即崩,也不给⼀个"有时⽣效有时不⽣效"的语义。这条我给满分。

6.6 ⚠ ⼀处顺序反直觉,⽽且 javadoc 没跟上:361 的 bindToSpringApplication ⼲的事是:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:552附近

Binder.get(environment).bind("spring.main", Bindable.ofInstance(this.properties));
⽽ this.properties 就是那个包私有的 ApplicationProperties ( [boot] core/spring-
boot/src/main/java/org/springframework/boot/ApplicationProperties.java:37 )——本基线把原先散在 SpringApplication 上的⼀堆字段(lazyInitialization、

bannerMode、registerShutdownHook……)全收进了这⼀个对象,所有 setter 都只是转发。

于是有了这条容易翻⻋的因果: spring.main.* 与 Java setter 是同⼀份状态,⽽ bind 发⽣在 prepareEnvironment ⾥,晚于你在 main ⽅法⾥调 setter。 结论是:

配置⽂件⾥的 spring.main.* 会覆盖你代码⾥写死的 setter,不是反过来。

"我明明 setBannerMode(OFF) 了,为什么 banner 还是打出来了"——因为有⼈在 yml ⾥写了 spring.main.banner-mode=console ,⽽它后到。

七、Banner:⼀⾏ contains("liquibase-core") 讲⼀个故事

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplicationBannerPrinter.java:84

private @Nullable Banner getTextBanner(Environment environment) {
String location = environment.getProperty(BANNER_LOCATION_PROPERTY, DEFAULT_BANNER_LOCATION);
Resource resource = this.resourceLoader.getResource(location);
try {
if (resource.exists() && !resource.getURL().toExternalForm().contains("liquibase-core")) { // :88
return new ResourceBanner(resource);
}
}
catch (IOException ex) {

// Ignore

}
return null;
}
选择顺序是三级: banner.txt ( spring.banner.location ,默认就是 "banner.txt" )→ 你 setBanner() 传的 fallback → 内置 SpringBootBanner ( :73-82 )。

第⼀级⾥那半⾏ !...contains("liquibase-core") ,是⼀枚真实世界打进框架源码的补丁: liquibase-core 这个 jar 的根⽬录⾥也放了⼀个 banner.txt ;不排掉的话,你的Spring 应⽤启动时会⼀本正经地打出 Liquibase 的 banner。

⚠ 但这也正是我要批评的地⽅:这是硬编码的⽩名单式排除,治标不治本。 判据是"URL ⾥含不含 liquibase-core 这个字符串"——换⼀个也在根⽬录塞 banner.txt 的依赖,

同样中招;⽽恰好路径⾥含这个串的你⾃⼰的 banner,反⽽会被误杀。更⼲净的做法应该是"只认应⽤⾃身 classpath 根、不认 jar 内资源",但那要动 ResourceLoader 的语义,代价更⼤。这⾏代码是⼀次诚实的妥协,不是⼀次优雅的设计——写在框架⾥,就永远删不掉了。

内置 banner 本体是个 Java ⽂本块( [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringBootBanner.java:35-42 ), STRAP_LINE_SIZE =

42 ( :46 )负责把版本号右对⻬——那个你看了⼀万遍的绿⾊ Spring 弹簧,对⻬宽度是 42。

🦴 默认 banner mode 在本基线⾥不再是⽆条件 CONSOLE。 java // [boot] core/spring-

boot/src/main/java/org/springframework/boot/ApplicationProperties.java:104 Mode getBannerMode(Environment environment) { if (this.bannerMode
!= null) { return this.bannerMode; } String applicationPropertyName =
LoggingSystemProperty.CONSOLE_STRUCTURED_FORMAT.getApplicationPropertyName(); Assert.state(applicationPropertyName != null,
"applicationPropertyName must not be null"); boolean structuredLoggingEnabled = environment.containsProperty(applicationPropertyName); //
:110 return (structuredLoggingEnabled) ? Mode.OFF : Banner.Mode.CONSOLE; // :111 } 开了结构化⽇志(console 结构化格式),banner 默认变 OFF。 讲得通:

结构化⽇志的每⼀⾏都要能被解析,中间夹⼀坨 ASCII 艺术就毁了。配置元数据也如实写了这句条件性默认( additional-spring-configuration-metadata.json:562 ),⽽且该条⽬故意没有 defaultValue 字段——因为默认值本身是条件的。

⚠ 但 setBannerMode 的 javadoc 仍写着 "Defaults to Banner.Mode.CONSOLE "。javadoc 与实现,本基线下已经对不上了。 这是我今天第⼆次遇到"别只信 javadoc":前

⾯ SpringApplicationRunListener 的 javadoc 要求实现类声明 public 构造函数,⽽官⽅⾃⼰的 EventPublishingRunListener 构造函数是包私有的( [boot]
core/spring-boot/src/main/java/org/springframework/boot/context/event/EventPublishingRunListener.java:63 ), SpringFactoriesLoader 照样能造出

来。读 Spring,永远以代码为准。

最后⼀⼿很有意思: printBanner 的返回值是个 PrintedBanner 装饰器,它会在 prepareContext ⾥被注册成单例 bean "springBootBanner" ( :402-404 )——打过的

banner 被留在了容器⾥,别⼈(⽐如 Actuator)想再打⼀次,拿现成的就⾏。

⼋、createApplicationContext:三个⻔卫,依次问同⼀个问题

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:579

protected ConfigurableApplicationContext createApplicationContext() {
ConfigurableApplicationContext context =
this.applicationContextFactory.create(this.properties.getWebApplicationType());
Assert.state(context != null, "ApplicationContextFactory created null context");
return context;
}

ApplicationContextFactory.DEFAULT 背后是 DefaultApplicationContextFactory ,⽽它⼲的事你已经⻅过⼀次了:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/DefaultApplicationContextFactory.java的 getFromSpringFactories

for (ApplicationContextFactory candidate : SpringFactoriesLoader.loadFactories(ApplicationContextFactory.class, ...)) {
T result = action.apply(candidate, webApplicationType);
if (result != null) { return result; } //★ 第⼀个⾮ null获胜
}
return (defaultResult != null) ? defaultResult.get() : null;

"排好队、⼀个个问、第⼀个给出⾮ null 答案的赢"——这是 Boot 全篇最⾼频的⼀种代码形状。 WebApplicationType.Deducer 是它, ApplicationContextFactory 是它,后⾯的 SpringBootExceptionReporter 还是它。认出这个形状,很多类就不必逐⾏读了。

两个 web ⼯⼚都注册在 [boot] module/spring-boot-web-server/src/main/resources/META-INF/spring.factories ⾥——注意:⼜是在 module ⾥,不在 core。它们的三个⽅法写法完全⼀样: (webApplicationType != XXX) ? null : ... ,不匹配就返回 null 让位,这正是"第⼀个⾮ null 获胜"能⼯作的前提。

兜底那条分⽀值得单看:

private ConfigurableApplicationContext createDefaultApplicationContext() {
if (!AotDetector.useGeneratedArtifacts()) { return new AnnotationConfigApplicationContext(); }
return new GenericApplicationContext();
}

AOT 模式下⽤的是不带注解扫描能⼒的 GenericApplicationContext ——因为图纸(BeanDefinition)已经在编译期⽣成好了,运⾏期不需要再扫⼀遍。这条对偶在三个⼯⼚⾥⼀致出现。

这⾥也是回答本章核⼼问题的第⼀格:裸 Framework ⾥"造哪个 context"是你在 new 那⼀⾏写死的;Boot ⾥它是被推断出来的。 但要看清:推断类型的链路(Deducer)和按类型造壳的链路(Factory)是解耦的两条——前者只回答"我是什么",后者只回答"那该造哪⼀件"。

九、prepareContext:点⽕前的⼗⼀件事,顺序⼀件都不能挪:380-419 ,四⼗⾏,⼗⼀件事。我把"为什么必须在这个位置"这⼀列补上,这⼀列才是重点:

⾏ 动作 为什么必须在这⼉

1 :383 context.setEnvironment(environment) 后⾯所有条件判断都要读它
2 :384 postProcessApplicationContext(context) 注⼊ beanNameGenerator / resourceLoader / conversionService
3 :385 addAotGeneratedInitializerIfNecessary(...)
要把 AOT initializer 插到列表最前( :434 initializers.addAll(0,

...) ),必须早于第 5 步4:386-392设 allowCircularReferences / allowBeanDefinitionOverriding refresh ⼀开始就会⽤ beanFactory,晚⼀步就没⽤了

5 :393 applyInitializers(context) initializer 要能改图纸、加 BFPP

6 :394 listeners.contextPrepared → ApplicationContextInitializedEvent7 :395 bootstrapContext.close(context) 储物柜的东⻄必须在这⼀刻搬进容器8:396-399logStartupInfo + logStartupProfileInfo 此时 profile 已定、⽇志系统已初始化9:401-404注册 springApplicationArguments / springBootBanner 两个单例 必须在 refresh 前,否则别的器注⼊不到10:405-411按需加 LazyInitializationBeanFactoryPostProcessor / KeepAlive /PropertySourceOrderingBeanFactoryPostProcessorBFPP 必须在 refresh 前挂上11:412-418

load(context, sources) + contextLoaded → ApplicationPreparedEvent 最后⼀步:把主配置类变成图纸

9.1 两个默认值,Boot 把 Framework 反着设这是全章最该记住的⼀处硬事实:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:387

if (beanFactory instanceof AbstractAutowireCapableBeanFactory autowireCapableBeanFactory) {
autowireCapableBeanFactory.setAllowCircularReferences(this.properties.isAllowCircularReferences()); // :388
if (beanFactory instanceof DefaultListableBeanFactory listableBeanFactory) {
listableBeanFactory.setAllowBeanDefinitionOverriding(
this.properties.isAllowBeanDefinitionOverriding()); // :390
}
}
两个字段在 ApplicationProperties ⾥都是裸 boolean 、⽆初始化器( :43 与 :49 )——即默认 false 。配置元数据双重确认: allow-circular-references 与 allow-

bean-definition-overriding 两条都明写 "defaultValue": false 。

⽽ Framework 那边呢?我回源查了:

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

boolean allowCircularReferences = true;

[framework] spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java:280 → return

!Boolean.FALSE.equals(this.allowBeanDefinitionOverriding); (字段是 @Nullable Boolean ,默认 null → 等于 true)
两边是反的。 同⼀份 @Configuration ,⽤ new AnnotationConfigApplicationContext(...) 跑得起来,换成 SpringApplication.run(...) 可能直接

BeanCurrentlyInCreationException 。

这算 Boot 的坑吗?我认为不算,这是⼀次值得称道的强硬。 循环依赖的三级缓存(ch11)是妥协不是优雅,⽽ bean 定义静默覆盖更是排障噩梦——把它们默认关掉,是把"约定"⽤在了正确的地⽅:约定应该约定"对的做法",⽽不是"省事的做法"。 Boot 甚⾄把配套的诊断都备好了:core 的 spring.factories ⾥注册着BeanCurrentlyInCreationFailureAnalyzer 与 BeanDefinitionOverrideFailureAnalyzer ,报错时给你的不是裸栈,是⼀段⼈话。

但代价要说清楚:这条差异从来不在"Spring Boot 快速⼊⻔"⾥出现,却是⽼项⽬从 Framework 迁 Boot 时最常⻅的第⼀个红屏。默认值的反转是⼀种沉默的破坏性变更——它只在别⼈的代码上炸。

9.2 ⼀个只做⼀件事的 BFPP,和"被踢到队尾三次"的 defaultProperties第 10 件事⾥那个 PropertySourceOrderingBeanFactoryPostProcessor 很值得看,因为它把整个类的价值压在⼀句话上:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:1590/**

* {@link BeanFactoryPostProcessor} to re-order our property sources below any
* {@code @PropertySource} items added by the {@link ConfigurationClassPostProcessor}.

*/

private static class PropertySourceOrderingBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {

@Override

public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } // :1604

@Override

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
DefaultPropertiesPropertySource.moveToEnd(this.context.getEnvironment()); // :1609
}
}
因果链是这样的: @PropertySource 是在 refresh 期间由 ConfigurationClassPostProcessor 处理的,它会往 Environment ⾥插新的 source;如果不管, defaultProperties

就会压在⽤户 @PropertySource 的头上。所以得在 refresh 期间再把它踢⼀次队尾。

于是 defaultProperties ⼀共被踢到队尾三次: prepareEnvironment ⾥⼀次( :358 )、这个 BFPP ⾥⼀次(refresh 期间)、 addOrMerge ⾃身维护⼀次。"永远最低优先级"这个承诺,是靠踢三次踢出来的。

9.3 ⼀处⼩⼩的彩蛋,和⼀条真断⾔// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:616

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

两条硬断⾔:泛型必须能被解析出来(所以 initializer 不能写成裸类型,也不能是个 lambda),且 context 必须是那个泛型类型的实例。第⼀条的错误消息⾥那个 "initializr" 是个真实存在于本基线⾥的拼写错误——读到这⼀⾏的时候我笑了⼀下:⼀座⼋⼗万⾏的坊,也会有⼯匠把牌⼦写错字。

⼗、交棒:三⾏代码,接回⼗⼆道⼯序// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:441

private void refreshContext(ConfigurableApplicationContext context) {
if (this.properties.isRegisterShutdownHook()) { //默认 true
shutdownHook.registerApplicationContext(context); // :443先拴绳
}
refresh(context); // :445再点⽕
}

Boot 对 refresh 的全部贡献:先把 context 登记进关机绳,再调⼀下。

绳先拴、⽕后点——这个顺序是对的:万⼀ refresh 半路炸了、⽽某些 bean 已经持有了外部资源,那根绳仍然能兜住。

进了 refresh() ,就是 ch15 那⼗⼆道⼯序,本章不重复。只钉⼀个很多⼈搞错的接缝:

端⼝是在 refresh() 内部绑定的,不是在 refreshContext 之后。 具体在第 9 道⼯序 onRefresh() ⾥—— [boot] module/spring-boot-web-
server/src/main/java/org/springframework/boot/web/server/servlet/context/ServletWebServerApplicationContext.java 的 onRefresh() 调
createWebServer() ,并注册⼀个名为 "webServerStartStop" 的 WebServerStartStopLifecycle 单例。

也就是说,当 ApplicationStartedEvent 发出来的时候,你的服务早就能接流量了;⽽ ApplicationReadyEvent 还在后⾯。这个时序差是很多"启动期健康检查抖动"问题的源头。

还有⼀件事这⾥必须点破边界,因为误解太普遍:⾃动配置不发⽣在 run() ⾥。 run() 的直接调⽤链⾛到 load(context, sources) 就停了——它只是把你的主配置类变成⼀张图纸。 @EnableAutoConfiguration 的展开,是在 refresh 的第 5 道⼯序⾥由 ConfigurationClassPostProcessor 触发的。本章的地界到 load 为⽌,那扇⻔在卷⼗⼆(ch38 起)才推开。

⼗⼀、落地:两把秒表、会被调两次的 Runner、和三根安全绳11.1 两把秒表,⼝径不同,别混⽤:322 的 afterRefresh 是个空⽅法( :764-765 ),纯粹留给⼦类。真正有意思的是紧接着的两个时间点:

startup.started() 在 :323 ——在 callRunners ( :328 )之前。所以⽇志⾥那句 Started MyApplication in 3.14 seconds 不含任何 Runner 的执⾏时间。
startup.ready() 在 :335 ——在 callRunners 之后。所以 ApplicationReadyEvent 携带的那个 Duration 才是含 Runner 的全程。

两个数字⼝径不同。 你在监控⾥画"启动耗时"曲线,取哪个,要先想清楚。

🦴 启动⽇志的第⼀个词,不⼀定是 "Started"。 java // [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:1771

static Startup create() { ClassLoader classLoader = Startup.class.getClassLoader(); return
(ClassUtils.isPresent("jdk.crac.management.CRaCMXBean", classLoader) && ClassUtils.isPresent("org.crac.management.CRaCMXBean", classLoader))
? new CoordinatedRestoreAtCheckpointStartup() : new StandardStartup(); } StandardStartup.action() 返回 "Started" ( :1803-1805 );⽽ CRaC 那个
返回 "Restored" ( :1822-1825 , restoreTime() >= 0 时)。 StartupInfoLogger ⾥那句话是 message.append(startup.action()) 拼出来的——从⼀个常量变成

⼀个⽅法调⽤,就是为了给 checkpoint/restore 留位置。 你哪天在⽇志⾥看到 Restored MyApplication in 0.03 seconds ,不是幻觉。

11.2 callRunners:⼀个 bean 可能被调两次// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:767

private void callRunners(ConfigurableApplicationContext context, ApplicationArguments args) {
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);
}
Comparator<Object> comparator = getOrderComparator(beanFactory)
.withSourceProvider(new FactoryAwareOrderSourceProvider(beanFactory, instancesToBeanNames));
instancesToBeanNames.keySet().stream().sorted(comparator).forEach((runner) -> callRunner(runner, args));
}
private void callRunner(Runner runner, ApplicationArguments args) { // :786
if (runner instanceof ApplicationRunner) { // :787
callRunner(ApplicationRunner.class, runner, (r) -> r.run(args));
}
if (runner instanceof CommandLineRunner) { // :790★ 独⽴ if,不是 else if
callRunner(CommandLineRunner.class, runner, (r) -> r.run(args.getSourceArgs()));
}
}

四个要点,每⼀个都是实战⾥踩过的:

1. Runner 是个包私有的标记接⼝( [boot] core/spring-boot/src/main/java/org/springframework/boot/Runner.java:26 , interface Runner { ,⽆ public )。

ApplicationRunner 与 CommandLineRunner 都 extends 它。所以——2. 两类 Runner 在同⼀个序列⾥排序,不是"先跑完所有 ApplicationRunner 再跑 CommandLineRunner"。谁先谁后,只看 @Order 。

  1. ⚠ ⼀个 bean 同时实现两个接⼝,会被调⽤两次( :787 与 :790 是两个独⽴的 if )。先 ApplicationRunner.run(args) ,后CommandLineRunner.run(args.getSourceArgs()) 。写初始化逻辑时这是个真实的幂等性事故源。
4. 任何 Runner 抛异常都会被包成 IllegalStateException("Failed to execute " + ...) ( :797-801 )往上抛——落进 :331 的 catch,整个 run 失败,容器被关闭。

Runner 不是"启动后随便跑跑",它是启动成功的⼀部分。

⽤ IdentityHashMap ⽽不是普通 Map,是为了按对象身份去重:同⼀个 bean 即使被两个类型名找到,也只出现⼀次。⽽ FactoryAwareOrderSourceProvider 的存在,是为了让写在 @Bean ⼯⼚⽅法上的 @Order 也能⽣效——它的类注释诚实地写着"Based on internal DefaultListableBeanFactory code",明说是从 Framework ⾥复刻的⼀段逻辑。这份诚实值得⼀提,但也暴露了⼀个事实:Boot 想复⽤ Framework 内部逻辑时,常常只能抄。

11.3 失败路径与关机绳// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:803

private RuntimeException handleRunFailure(@Nullable ConfigurableApplicationContext context, Throwable exception,
@Nullable SpringApplicationRunListeners listeners) {
if (exception instanceof AbandonedRunException abandonedRunException) {
return abandonedRunException; // :806★ 直接放⾏,⼀切清理都跳过
}
try {
try {
handleExitCode(context, exception); // :810算退出码
if (listeners != null) { listeners.failed(context, exception); } // :811发 ApplicationFailedEvent
}
finally {
reportFailure(getExceptionReporters(context), exception); // :816失败分析报告
if (context != null) {
context.close(); // :818
shutdownHook.deregisterFailedApplicationContext(context); // :819
}
}
}
catch (Exception ex) {
logger.warn("Unable to close ApplicationContext", ex); // :824
}
return (exception instanceof RuntimeException runtimeException) ? runtimeException
: new IllegalStateException(exception);
}

reportFailure ⾛的⼜是"第⼀个说 true 的赢":遍历 SpringBootExceptionReporter ,本基线只注册了⼀个 FailureAnalyzers ,它背后是⼗⼏个 FailureAnalyzer 。"端⼝被占⽤了"这类⼈话报错,就是从这条路出来的。 都没⼈认领,才落到 logger.error("Application run failed", failure) 。

⽽那根关机绳,是 Boot 与裸 Framework 差别最⼤的配件之⼀:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java:48

class SpringApplicationShutdownHook implements Runnable {
private static final int SLEEP = 50; // :50
private static final long TIMEOUT = TimeUnit.MINUTES.toMillis(10); // :52
private final Set<ConfigurableApplicationContext> contexts = new LinkedHashSet<>(); // :58
private final Set<ConfigurableApplicationContext> closedContexts =
Collections.newSetFromMap(new WeakHashMap<>()); // :60★ 弱引⽤

...

}
它在 SpringApplication ⾥是 static final ( :207 )——全 JVM 唯⼀的⼀根绳,所有 SpringApplication 共享。Framework 那边的 registerShutdownHook()
( [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:1069 )则是每个 context 各挂⼀个 JVM

线程,⽽且要你⾃⼰想起来调。

最⻅功⼒的是 closeAndWait :

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplicationShutdownHook.java:143

private void closeAndWait(ConfigurableApplicationContext context) {
if (!context.isActive()) { return; }
context.close();
try {
int waited = 0;
while (context.isActive()) { // :150★ 轮询等它真的死透
if (waited > TIMEOUT) { throw new TimeoutException(); }
Thread.sleep(SLEEP);
waited += SLEEP;
}
}

...

}

⽅法上的注释把理由写死了:"We can't assume that just because the close method returns that the context is actually inactive. It could be that another thread is still in theprocess of disposing beans."

close() 返回 ≠ 关完了。 50 毫秒⼀轮,最多等 10 分钟。这是⼀个被⽆数⽣产事故教出来的循环。

顺带把"我的⾮ web 应⽤⼀启动就退出了"这个经典问题也解掉: spring.main.keep-alive=true (默认 false)会在 prepareContext 挂⼀个 KeepAlive listener( :408-410 ),

它在 ContextRefreshedEvent 时起⼀个线程:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:1714

Thread thread = new Thread(() -> {
while (true) {
try { Thread.sleep(Long.MAX_VALUE); }
catch (InterruptedException ex) { break; }
}
});
if (this.thread.compareAndSet(null, thread)) {
thread.setDaemon(false); // :1725★ ⾮守护
thread.setName("keep-alive"); // :1726
thread.start();
}

⼀个什么都不⼲、只负责睡觉的⾮守护线程,把 JVM 钉在地上。 朴素得让⼈发笑,但这就是正确答案:JVM 退出的判据是"没有⾮守护线程了",那就给它⼀个。

⼗⼆、✨ 全章最妙的⼀⼿:AOT 的"假启动"

留到最后讲,因为它同时⽤上了前⾯三处零件。

问题:AOT 处理需要⼀个"图纸都装配好了、但还没点⽕"的容器,好把 bean 定义在编译期固化下来。可 main ⽅法是⽤户写的, run() ⼀路跑到底就把应⽤真的启动了。怎么在不改⽤户⼀⾏代码的前提下,拿到那个"装配好但没 refresh"的容器?

Boot 的答案分三处,缺⼀不可:

第⼀处,⼀个 ThreadLocal 后⻔:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplication.java:1462

public static <T> T withHook(SpringApplicationHook hook, ThrowingSupplier<T> action) {
applicationHook.set(hook);
try { return action.get(); }
finally { applicationHook.remove(); }
}

它在 getRunListeners 的 :458 被消费,临时往 listener 列表⾥追加⼀个。

第⼆处,⼀个只实现⼀个回调的匿名 listener——⽽那个回调⼲的事是抛异常:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/SpringApplicationAotProcessor.java:112@Override

public SpringApplicationRunListener getRunListener(SpringApplication application) {
return new SpringApplicationRunListener() {

@Override

public void contextLoaded(ConfigurableApplicationContext context) {
throw new AbandonedRunException(context); // :117★ 掐断
}
};
}

第三处, handleRunFailure 开头那条特判( :805-807 ): AbandonedRunException 直接放⾏,不算失败、不发事件、不出报告、不关容器。

于是整条戏是这样演的( SpringApplicationAotProcessor.java:59-71 + :123-137 ):反射把⽤户的 main ⽅法调起来 → ⽤户的 SpringApplication.run ⼀切如常地跑

→ 跑到 contextLoaded 那⼀刻,hook 塞进去的那个 listener 抛出 AbandonedRunException ,把还没点⽕的 context 装在异常⾥扔出来 → handleRunFailure 认出这是"故意的",原样放⾏ → 外层 catch 住,把 context 从异常⾥掏出来。

⽤异常做流程控制,通常是要挨骂的。但在这⾥,它是唯⼀优雅的解法。 因为要表达的语义恰恰就是"我要在这⼀点⾮正常地、⼲净地退出整条调⽤栈",⽽这条栈的中间部分是⽤户代码,你碰不得。

⚠ 暗礁也随之⽽来: applicationHook 是 ThreadLocal ( :209 )。如果⽤户的 main ⽅法把 SpringApplication.run 丢到别的线程去跑,hook 就丢了,AOT 处理会报 "No

application context available after calling main method of '...'. Does it run a SpringApplication?" ( SpringApplicationAotProcessor.java:134-

136 )。这个错误消息写得很体贴,但根因是 ThreadLocal 的⽼⽑病——⼀条挂在本⼈身上的绳,换了⼈就断。这个句式你在 ch23 讲事务时⻅过,在这⾥⼜⻅了⼀次。

⼗三、回答:它与裸 Framework 的差别到底在哪现在可以把整章收成⼀张表了。每⼀格我都回过源。

维度

裸 Framework( new
AnnotationConfigApplicationContext(C.class) )
Boot( SpringApplication.run(C.class, args) )

容器类型 你在 new 那⼀⾏写死 由 WebApplicationType + ApplicationContextFactory 推断Environment 类型StandardEnvironment 三种之⼀,⽽且可能中途整体换壳profile 从哪读 AbstractEnvironment 直接读 spring.profiles.active override 成 return null ,全交给 ConfigData配置⽂件 没有。要 @PropertySource ⼀条条写 application.yml + profile + import,在 :356 那⼀刻处理完命令⾏参数 没有 SimpleCommandLinePropertySource addFirst,并注册成单例 bean松散绑定 没有 configurationProperties 元 source addFirst ,挂两次

循环依赖默认 允许( AbstractAutowireCapableBeanFactory.java:131 = true) 显式关掉(false)

bean 定义覆盖默认

允许( DefaultListableBeanFactory.java:280 ) 显式关掉(false)

refresh 之前的事件不可能有(multicaster 在第 8 道⼯序才建) 四个,⾛ EventPublishingRunListener ⾃带的对讲机refresh 之后的事件只有 ContextRefreshedEvent

多出 ApplicationStartedEvent / ApplicationReadyEvent + 两个 AvailabilityChangeEvent (K8s

探针语义就落在这两⾏)

启动后跑业务代码你⾃⼰在 new 完之后写 ApplicationRunner / CommandLineRunner ,统⼀排序关机 每 context ⼀个 JVM hook,要你⼿动调 默认开,全 JVM ⼀根绳,等到真的关完,⽀持⾃定义 handler失败诊断 裸栈 SpringBootExceptionReporter → FailureAnalyzers → ⼀串 FailureAnalyzer退出码 没这个概念 ExitCodeGenerator / ExitCodeExceptionMapper / ExitCodeEvent

计时与可观测 没有 Startup (含 CRaC) + 七个 StartupStep

Banner 没有 三级选择,还注册成 bean

refresh() 本

身— ⼀个字没改为什么必须是"包在外⾯"⽽不是"改在⾥⾯"? 三条约束逼出了这个形状:

  1. refresh() 是 API 契约。 任何⼈拿到 ConfigurableApplicationContext 都能调它。Boot ⼀旦在⾥⾯塞私货,"⽤ Framework 的⼈"和"⽤ Boot 的⼈"看到的容器语义就分叉了——那才是灾难。
  1. 很多决策按定义就发⽣在容器之前。 "我是 servlet 还是 reactive"决定了要造哪个 context 类;"配置⽂件⾥写了什么"决定了 profile、web 类型、要不要打 banner。这些事只能在外⾯做。
  1. 很多交付按定义就发⽣在容器之后。 "应⽤真的可以接流量了"这个语义, ContextRefreshedEvent 表达不了——它只说明器都造好了,不说明 Runner 跑完了。所以 Boot需要 started / ready 这两个⾃⼰的刻度。

⼀句话:

SpringApplication 不是"更好的 ApplicationContext",它是 ApplicationContext 的⽣命周期编排器。 容器还是那个容器;Boot 做的,是把"造它之前要做什么、造好之后要通知谁"这件事,从每个应⽤的 main ⽅法⾥收编成了⼀条标准流⽔线。

⽤坊⾥的话说:从前每个匠⼈开⼯前都要⾃⼰跑⼆⼗⼏趟腿——问料在哪、翻账本、点名、挂牌⼦、拴绳。Boot 把这⼆⼗⼏趟腿印成了⼀张检查单,发给每个⼈。你还是可以⾃⼰跑(每⼀格都留了 override 点和 SPI),但默认你不⽤跑了。