源码小说CodeStory
登录
上一章

37,217 字 · 约 93 分钟

下一章
字体

主题

版式

第43章 卷十三 · 周边 · 坊里自带门市:内嵌容器与 Actuator

卷⼗三 · 周边坊⾥⾃带⻔市:内嵌容器与 Actuator「我不是被摆进⻔市的。⻔市是我摆出来的。」 —— ServletWebServerApplicationContext 的⾃⽩⼀、开场:⼀句 java -jar 背后的改朝换代前四⼗⼀章,我们⼀直在坊⾥打转:图纸怎么攒、器怎么造、榫卯怎么扣、壳怎么套、柜台怎么派单。有⼀件事我们⼀直避⽽不谈——这座坊,到底摆在哪⼉?

在 war 的年代,答案很清楚:坊摆在⻔市⾥。Tomcat 先起来,扫 webapps/ ,读 web.xml ,由 ContextLoaderListener 把 Spring 的总装房造出来。容器是房东,Spring 是租客。

你交付的是⼀卷 war,房东决定它什么时候被展开、什么时候被销毁、跑在哪个 JVM ⾥、和哪⼏个邻居共⽤⼀个进程。你的应⽤没有 main() ,它连"⾃⼰什么时候活过来"都做不了主。

内嵌模型把这句话整个倒过来念:

SpringApplication.run() → 造出⼀个 ServletWebServerApplicationContext → refresh() → 在 onRefresh() ⾥从⾃⼰的 BeanFactory ⾥找出⼀个

ServletWebServerFactory ,⽤它把 Tomcat 造出来。

坊⾃⼰开了个⻔市。房东和租客换了位置——容器降级成了⼀件普通的器,和你的 UserService ⼀样,是照图纸造出来、由作坊管着⽣⽼病死的。

这不是修辞。这是字⾯意思。证据只有⼗⼆⾏:

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

protected ServletWebServerFactory getWebServerFactory() {

// Use bean names so that we don't consider the hierarchy

String[] beanNames = getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);
if (beanNames.length == 0) {
throw new MissingWebServerFactoryBeanException(getClass(), ServletWebServerFactory.class,
WebApplicationType.SERVLET);
}
if (beanNames.length > 1) {
throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple "
+ "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));
}
return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
}

getBean() 。 ⼀个 HTTP 服务器,是被 getBean() 出来的。

三处细节值得停⼀停:

第⼀,那句注释—— // Use bean names so that we don't consider the hierarchy 。它故意不看⽗上下⽂。看似多余的洁癖,后⾯会兑现成⼀个很硬的能⼒:管理端⼝独⽴时,⼦上下⽂能拥有⾃⼰的⼀台 Tomcat,⽽不会误认⽗上下⽂那台(⻅第九节)。

第⼆,找到 0 个,抛的不是⼲巴巴的 NoSuchBeanDefinitionException ,⽽是专⻔造的 MissingWebServerFactoryBeanException ——它继承NoSuchBeanDefinitionException ,并配了⼀个 FailureAnalyzer ,好让你在控制台看到⼈话⽽不是堆栈。

第三,找到 >1 个直接炸。不是"取第⼀个",不是"按 @Primary 挑"。内嵌容器⼯⼚必须唯⼀。 这个决定很硬⽓:⼀个进程⾥同时冒出两个"我要开⻔市"的图纸,不管你想⼲什么,都⼤概率是配错了。

⼆、三明治时序:616、622、625反转的代价,全都藏在 refresh() 的三⾏之间。

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

public void refresh() throws BeansException, IllegalStateException {

...

onRefresh(); // :616 ←造服务器(不接客)
registerListeners(); // :619
finishBeanFactoryInitialization(beanFactory); // :622 ←所有⾮懒单例在这⾥才实例化
finishRefresh(); // :625 ←启服务器(绑端⼝)

...

}

造在 616,启在 625,⽽"把所有单例造出来"卡在中间的 622。 这是⼀个三明治,⽽且是全章的⻣架——后⾯每⼀处精妙和每⼀处坑,都挂在这根⻣头上。

为什么必须是这个顺序?因为 DispatcherServlet 需要⼀个可⽤的 ServletContext 才能被注册进去,⽽ ServletContext 只有在容器真正 start 之后才存在。所以服务器必须早于单例实例化就⽴起来。

但服务器⼀旦⽴起来,端⼝就通了,请求就能进来了——打在⼀个只造了⼀半的应⽤上。

Spring Boot 把这个两难写进了接⼝契约,写在 javadoc 的第⼀句:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/servlet/ServletWebServerFactory.java:33/**

* Gets a new fully configured but paused {@link WebServer} instance. Clients should
* not be able to connect to the returned server until {@link WebServer#start()} is
* called (which happens when the {@code ApplicationContext} has been fully
* refreshed).

*/

WebServer getWebServer(ServletContextInitializer... initializers);

"fully configured but paused" ——完全配置好,但暂停着。这七个字是本章的题眼。它要求实现⽅做到⼀件反直觉的事:服务器内部完整地跑起来,⽽对外⼀个⼊⼝都不开。

Tomcat 是怎么做到的?

三、Tomcat 的三⼿障眼法翻开 TomcatWebServer ,你会看到本章最精妙、也最"不体⾯"的⼀段代码。

// [boot] module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/TomcatWebServer.java:113

private void initialize() throws WebServerException {
logger.info("Tomcat initialized with " + getPortsDescription(false));
synchronized (this.monitor) {
try {
addInstanceIdToEngineName();
Context context = findContext();
context.addLifecycleListener((event) -> {
if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {

// Remove service connectors so that protocol binding doesn't// happen when the service is started.

removeServiceConnectors();
}
});
disableBindOnInit();

// Start the server to trigger initialization listeners

this.tomcat.start();

// We can re-throw failure exception directly in the main thread

rethrowDeferredStartupExceptions();

...

startNonDaemonAwaitThread();
}
catch (Exception ex) {
stopSilently();
destroySilently();
throw new WebServerException("Unable to start embedded Tomcat", ex);
}
}
}

这段代码在 TomcatWebServer 的构造函数⾥就跑完了。 也就是说, getWebServer() 返回的那⼀刻, this.tomcat.start() 已经调过了。Tomcat 真的启动了。

那"paused"从何谈起?靠三⼿障眼法:

第⼀⼿, disableBindOnInit() (同⽂件 :181 ):挨个把 Connector 的 bindOnInit 设成 false ,让 Tomcat 在 init 阶段不去 bind socket。

第⼆⼿,在 Context 的 START_EVENT ⾥把连接器整个偷⾛( removeServiceConnectors() ,同⽂件 :172 ):Tomcat ⼀喊"我要开始了",监听器⽴刻把所有 Connector 从Service 上摘下来,存进⼀个私有 map。等 Service 真正⾛到"启动连接器"那⼀步时,⼿上根本没有连接器可启动。

第三⼿,把 load-on-startup 掏空:

// [boot] module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/TomcatEmbeddedContext.java:54@Override

public boolean loadOnStartup(Container[] children) {
// deferred until later (see deferredLoadOnStartup)
return true;
}

覆写了,返回 true (告诉 Tomcat "我⼲完了"),但⼀件事没⼲。所有 load-on-startup 的 servlet——包括 DispatcherServlet ——这时候都不初始化。

于是就有了那个奇景:Tomcat 完整地活着,线程池转着, ServletContext 可⽤,但它是⼀座没有⻔的房⼦。

三个⽉后, finishRefresh() ⾛到 WebServerStartStopLifecycle.start() ,三⼿障眼法被逐⼀撤销:

// [boot] module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/TomcatWebServer.java:226

public void start() throws WebServerException {
synchronized (this.monitor) {
if (this.started) { return; }
try {
addPreviouslyRemovedConnectors(); //把连接器装回去 ——这⼀刻才 bind端⼝
Connector connector = this.tomcat.getConnector();
if (connector != null && this.autoStart) {
performDeferredLoadOnStartup(); //现在才 init load-on-startup的 servlet
}
checkThatConnectorsHaveStarted();
this.started = true;
logger.info(getStartedLogMessage());
}

...

}
}

连接器装回去、端⼝ bind、 DispatcherServlet 初始化,顺序⼀丝不乱。那句你⻅过⼀万次的 Tomcat started on port 8080 (http) with context path '/' 就是在这

⾥打出来的( getStartedLogMessage() ,同⽂件 :257 )。
🦴 ⻣灰级细节:两条⽇志,两个端⼝。 initialize() ⾥那句 Tomcat initialized with ... ⽤的是 getPortsDescription(false) ——配置端⼝;⽽ start() ⾥那句

Tomcat started on ... ⽤的是 getPortsDescription(true) ——真实的本地端⼝。所以当你配 server.port=0 (随机端⼝),第⼀条⽇志会⽼⽼实实打个 0 ,第⼆条才告诉你真相。很多⼈以为第⼀条是 bug,其实那正是它该说的话:那⼀刻端⼝还没绑,它除了 0 什么都不知道。

🦴 另⼀个: container-0 线程是哪来的? 就是 startNonDaemonAwaitThread() (同⽂件 :211 )。源码注释写得很朴实:

// Unlike Jetty, all Tomcat threads are daemon threads. We create a// blocking non-daemon to stop immediate shutdownTomcat 的线程全是 daemon, main() ⼀返回 JVM 就退了。所以 Boot 额外起了⼀个⾮ daemon 线程死死 await() 住。你 jstack ⾥那个叫 container-0 的线程,唯⼀的职责就是"活着,别让 JVM ⾛"。 ⼀个内嵌容器要活下去,居然需要专⻔雇⼀个⼈站着不动——这就是"坊⾥开⻔市"要付的第⼀笔房租。

✨ 顺便⼀提,Jetty 的思路⼀模⼀样,招数更省事:

// [boot] module/spring-boot-jetty/src/main/java/org/springframework/boot/jetty/JettyWebServer.java:121(⽚段)

this.connectors = this.server.getConnectors();
JettyWebServer.this.server.setConnectors(null);

...

this.server.start();

缓存连接器 → 置空 → start → 到 start() 时装回去。 同⼀个抽象下,Tomcat 需要额外处理 bindOnInit 和 load-on-startup ,Jetty 不需要。这是"接⼝/实现分离"最实在的⼀种体现:契约只有⼀句"paused",各家怎么骗⾃⼰的服务器,是各家的事。

四、异常的搬运⼯还有⼀处⼩⼿笔,不精妙,但很体贴。

Tomcat 跑 ServletContainerInitializer 是在⾃⼰的线程与⾃⼰的⽣命周期⾥。如果 Spring 上下⽂启动失败(⽐如某个 bean 造不出来),异常会先被 Tomcat 抓⾛、包成⼀堆 LifecycleException 、打⼀屏⽇志,最后你看到的是⼀坨与真相⽆关的噪⾳。

Boot 的解法是把异常存下来,搬回主线程再扔:

// [boot] module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/servlet/DeferredServletContainerInitializers.java:38@Override

public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
try {
for (ServletContextInitializer initializer : this.initializers) {
initializer.onStartup(servletContext);
}
}
catch (Exception ex) {
this.startUpException = ex;

// Prevent Tomcat from logging and re-throwing when we know we can// deal with it in the main thread, but log for information here....

}
}

@Override

public void rethrow() throws Exception {
if (this.startUpException != null) { throw this.startUpException; }
}

对应 initialize() ⾥那⾏ rethrowDeferredStartupExceptions() 。吞掉、存住、换个线程再抛。 ⽬的只有⼀个:让你看到⼲净的 BeanCreationException ,⽽不是Tomcat 的哀嚎。

⼀个框架愿意为"错误信息可读性"专⻔写⼀个类,这件事值得记⼀笔。绝⼤多数框架的做法是——让异常⾃然冒泡,反正堆栈⾥都有。

五、Phase 算术:1024、1024、512服务器不是 bean,但它必须跟着 bean 的⽣命周期⾛。Boot 的做法是在 createWebServer() 末尾往 BeanFactory ⾥⼿⼯塞两个单例(不是 @Bean ,是 registerSingleton ):

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

private void createWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = getServletContext();
if (webServer == null && servletContext == null) {

...

webServer = factory.getWebServer(getSelfInitializer());
this.webServer = webServer;

...

getBeanFactory().registerSingleton("webServerGracefulShutdown",
new WebServerGracefulShutdownLifecycle(webServer));
getBeanFactory().registerSingleton("webServerStartStop", new WebServerStartStopLifecycle(this, webServer));
}
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
initPropertySources();
}

顺带请注意那个 else if 分⽀: servletContext != null 就是 war 部署的路径——容器已经存在,只需要把 initializer 跑⼀遍。同⼀个上下⽂类,靠 getServletContext()

是否为 null,同时⽀撑"应⽤启动容器"和"容器装载应⽤"两种世界观。反转没有把⽼路砍掉,它只是让⽼路变成了⼀个 else if 。

两个 Lifecycle 的先后,靠 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;
⽽ [framework] spring-context/src/main/java/org/springframework/context/SmartLifecycle.java:82 ⾥ DEFAULT_PHASE = Integer.MAX_VALUE 。算⼀下:
START_STOP = MAX − 2048
GRACEFUL = MAX − 1024

普通组件 = MAX启动按 phase 升序:先绑端⼝ → 再挂优雅停机 → 最后普通组件。 停⽌按 phase 降序:先停普通组件 → 再优雅停机(不收新请求、等在途请求跑完)→ 最后真停服务器。

那两个 1024,就是给"优雅停机必须晚于业务组件停机、⼜必须早于真停机"留出的空隙。三层洋葱,靠两个常量拧出来。

WebServerGracefulShutdownLifecycle 还有⼀处很有脾⽓的写法:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/context/WebServerGracefulShutdownLifecycle.java:48(⽚段)

@Override

public void stop() {
throw new UnsupportedOperationException("Stop must not be invoked directly");
}

LifecycleProcessor 只会调回调版 stop(Runnable) 。谁要是绕过去直接调⽆参 stop() ,说明⽤法就是错的——直接炸给你看,不给静默失败的机会。

⭐ 本基线独有的⼀条: isPauseable() 。 两个 Lifecycle 都覆写了它,都返回 false :

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

public boolean isPauseable() {
return false;
}
接⼝那侧是 [framework] spring-context/src/main/java/org/springframework/context/SmartLifecycle.java:121 , default boolean isPauseable() { return

true; } ,javadoc 标着 @since 7.0 。含义是:Framework 7 新增了"暂停上下⽂"的能⼒,⽽ web 服务器明确拒绝参与暂停—— pause() 时业务组件可以歇着,服务器照常开着。

这是本基线(Framework 7.1.0-SNAPSHOT / Boot 4.2.0-SNAPSHOT)才有的细节,Boot 3 的⽂章⾥⼀个字都没有。
🦴 停机超时藏在两处,数不⼀样。 Framework 侧 DefaultLifecycleProcessor 的裸默认是 10 秒( [framework] spring-
context/src/main/java/org/springframework/context/support/DefaultLifecycleProcessor.java:124 , timeoutPerShutdownPhase = 10000 ),⽽ Boot 把它改成了
30 秒( [boot] core/spring-boot-
autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/LifecycleProperties.java:36 , Duration.ofSeconds(30) ,前缀

spring.lifecycle )。查资料时看到"10 秒"别急着信,得先问是哪⼀层的默认值。

⚠ 暗礁: server.shutdown 在本基线默认已经是 GRACEFUL 。

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/autoconfigure/ServerProperties.java:107

private Shutdown shutdown = Shutdown.GRACEFUL;
⽽⼯⼚类⾃⼰的裸默认仍是 IMMEDIATE ( [boot] module/spring-boot-web-
server/src/main/java/org/springframework/boot/web/server/AbstractConfigurableWebServerFactory.java:71 )——只有⾛⾃动配置、被

ServletWebServerFactoryCustomizer 覆盖过,才会变成 GRACEFUL。"优雅停机默认关闭,需要⼿动开"是 Boot 2.3 到 3.x 全⽹都在讲的常识,本基线已经反过来了。 照抄旧⽂章会说反。

六、反转失去了什么前⾯全是夸。现在该算账了。

反转最漂亮的⼀⾯是:可执⾏ jar、可容器化、开发体验(改⼀⾏代码按⼀下重启,不⽤ deploy)、每个应⽤独占⼀台服务器所以再没有"隔壁应⽤把 JVM 拖垮了"。这些好处⼤到没什么可争的。

但那个三明治时序——造在 616、单例在 622——是要还的。

// [boot] core/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java:225

private <T> List<Entry<String, T>> getOrderedBeansOfType(ListableBeanFactory beanFactory, Class<T> type, Seen seen) {
String[] names = beanFactory.getBeanNamesForType(type, true, false);
Map<String, T> map = new LinkedHashMap<>();
for (String name : names) {
if (!seen.contains(type, name) && !ScopedProxyUtils.isScopedTarget(name)) {
T bean = beanFactory.getBean(name, type); // ←就是这⼀⾏

...

}
}

...

}

这段代码跑在 onRefresh() ⾥,也就是 616 ⾏。它对每⼀个 Filter 类型的 bean 调 getBean() 。

后果是连锁的:所有 Filter bean 会在 refresh 中途被提前实例化 → 它们的依赖被连带提前实例化 → ⽽那时候某些 BeanPostProcessor 可能还没就位。 于是你会撞上那类最难查的怪事:注⼊进 Filter 的那个 service,没有被套壳, @Transactional 静默失效;或者 @ConfigurationProperties 绑定还没完成,拿到的是⼀堆 null。

它不报错。它只是不对。

官⽅给的逃⽣舱是 DelegatingFilterProxyRegistrationBean ,javadoc 说得⾮常直⽩:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/web/servlet/DelegatingFilterProxyRegistrationBean.java:36

* The bean name of the actual delegate {@link Filter} should be specified using the
* {@code targetBeanName} constructor argument. Unlike the {@link FilterRegistrationBean},
  • referenced filters are not instantiated early. In fact, if the delegate filter bean is
* marked {@code @Lazy} it won't be instantiated at all until the filter is called.

注册的是名字,不是对象。 这也正是 Spring Security 的 springSecurityFilterChain ⼀定要⾛ DelegatingFilterProxy 的原因——安全过滤器链上挂着半个 Spring ⽣态,提前实例化是灾难。

官⽅⽂档甚⾄专⻔为这件事写了⼀句认输:

// [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/web/servlet.adoc:612In an embedded container setup, the ServletContext is set as part of server startup whichhappens during application context initialization.Because of this beans in the ApplicationContext cannot be reliably initialized with a ServletContext."cannot be reliably initialized"——不能可靠地初始化。这是⽂档⾥罕⻅的直⽩措辞,承认反转带来了⼀个⽆法通过 API 设计消除的时序缺⼝,只能靠"注⼊ ApplicationContext ⽤的时候再取"或者"监听 ApplicationStartedEvent "绕。

⚠ 还有⼀条更隐蔽的:只要你定义了任何⼀个 ServletContextInitializer bean,Servlet/Filter bean 的⾃动注册就整个关掉。 这写在类级 javadoc ⾥:

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

* To prevent double registration, the use of {@link ServletContextInitializer} beans
  • will disable automatic Servlet and Filter bean registration.

要么全⾃动,要么全⼿动,没有中间态。第⼀次为了给某个 Filter 设 order ⽽加了个 FilterRegistrationBean ,结果另外三个 Filter 集体失踪的⼈,不⽌⼀个。

顺便把⾃动注册的默认规则钉死(别背⽹上的):

// [boot] core/spring-boot/src/main/java/org/springframework/boot/web/servlet/ServletContextInitializerBeans.java:298

String url = (totalNumberOfSourceBeans != 1) ? "/" + beanName + "/" : "/";
if (beanName.equals(DISPATCHER_SERVLET_NAME)) {
url = "/"; // always map the main dispatcherServlet to "/"
}
只有⼀个 Servlet bean → 映射 / ;多个 → 各⾃ /<beanName>/ ;但名叫 dispatcherServlet 的永远是 / 。 Filter 默认映射 /* ( [boot] core/spring-
boot/src/main/java/org/springframework/boot/web/servlet/AbstractFilterRegistrationBean.java:50 ), asyncSupported 默认 true (同包
DynamicRegistrationBean.java:49 )。

六之⼆、⼀个陪跑⼗年的名字,只剩六个字⺟本基线还有⼀条更冷的账。

我在两个仓⾥翻 Undertow,结果是这样的: module/ 下没有 spring-boot-undertow ; starter/ 下没有 spring-boot-starter-undertow ;整个 documentation/ ⾥零命

中。全仓 grep -ril undertow 只有⼀个⽂件命中:

// [boot] config/checkstyle/import-control.xml:201

<subpackage name="tomcat|undertow|jetty|reactor" regex="true">

⼀条没清⼲净的 checkstyle 正则。⼀个陪伴 Spring Boot ⼗年的内嵌容器,在这份快照⾥只剩六个字⺟,躺在⼀条构建规则⾥。 ⽂档明写( [boot] documentation/spring-boot-

docs/src/docs/antora/modules/reference/pages/web/servlet.adoc:606 )可⽤的只有 TomcatServletWebServerFactory 与 JettyServletWebServerFactory 。

对⽤ Undertow 的项⽬,这意味着升级到 Boot 4 没有平滑路径——不是配置项改名,是模块没了。这就是"依赖⼀个可插拔抽象"的真实⻛险:抽象保证了你换实现很容易,但它保证不了实现⼀直在。

顺带记⼀笔本基线的另⼀处更名:

// [boot] starter/spring-boot-starter-web/build.gradle:21

description = "Starter for building web, including RESTful, applications using Spring MVC.
Uses Tomcat as the default embedded container (deprecated in favor of spring-boot-starter-webmvc)"

那个你敲过⼀千遍的 spring-boot-starter-web ,在本基线的 description ⾥已经写着 deprecated,新名字是 spring-boot-starter-webmvc 。料包也是会改名的。

七、Customizer:三层梯度与⼀次泛型的赔款内嵌容器要可定制,Boot 给了三层,抽象梯度⼀层⽐⼀层低:

第⼀层,属性。 server.port / server.shutdown / server.servlet.context-path ——由 ServletWebServerFactoryCustomizer ⽤ PropertyMapper ⼀条条搬进⼯⼚。

第⼆层, WebServerFactoryCustomizer<T> 。 跨服务器的通⽤扩展点,⼀个函数式接⼝:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizer.java:40@FunctionalInterface

public interface WebServerFactoryCustomizer<T extends WebServerFactory> {
void customize(T factory);
}
第三层,服务器原⽣ Customizer。 TomcatConnectorCustomizer / TomcatContextCustomizer / TomcatProtocolHandlerCustomizer<T> / JettyServerCustomizer

——直接把 Tomcat 的 Connector 、Jetty 的 Server 塞你⼿⾥。这是逃⽣舱:抽象兜不住的,就把原件递出来。⽂档对这层的定位说得很坦⽩: Spring Boot tries as muchas possible to expose common settings, but this is not always possible.看第⼆层的执⾏机制,有⼀处很值得写:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizerBeanPostProcessor.java:71

private void postProcessBeforeInitialization(WebServerFactory webServerFactory) {
LambdaSafe.callbacks(WebServerFactoryCustomizer.class, getCustomizers(), webServerFactory)
.withLogger(WebServerFactoryCustomizerBeanPostProcessor.class)
.invoke((customizer) -> customizer.customize(webServerFactory));
}

LambdaSafe 是什么?是给泛型擦除交的赔款。

WebServerFactoryCustomizer<T> 是函数式接⼝。当你⽤ lambda 写⼀个 WebServerFactoryCustomizer<TomcatServletWebServerFactory> 时,运⾏时那个 T 根本不存

在——lambda 没有可供反射读取的泛型签名。BPP 拿到⼀个 Jetty ⼯⼚时,没法在调⽤前判断"这个 customizer 是不是给 Tomcat ⽤的",只能调下去,然后接住

ClassCastException ,静默跳过(记⼀条 debug ⽇志)。

这是很诚实的⼀段代码,也是很值得警惕的⼀段:你的 customizer 没⽣效,可能不是没被发现,⽽是被 ClassCastException 悄悄吃掉了,⽽⽇志在 debug 级别。 ⽤具名类⽽不是lambda 就能让泛型可读、让匹配⾛正路——这是"少写⼏个字符"要付的隐性代价。

还有两处细节呼应前⽂:

private Collection<WebServerFactoryCustomizer<?>> getCustomizers() {
if (this.customizers == null) {

// Look up does not include the parent context...

}
}

⼜是"不看⽗上下⽂"。 和第⼀节 getWebServerFactory() 的注释⼀模⼀样。这个策略在本章会出现三次,每⼀次都是为同⼀件事服务(⻅第九节)。

⽽ getBeansOfType(WebServerFactoryCustomizer.class, false, false) 两个 false :不含⾮单例、不允许 eager init——避免为了找 customizer ⽽把⼀堆

FactoryBean 提前催熟。

⚠ 暗礁:customizer 被调⽤得⾮常早。 javadoc 亲⾃警告:

// [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/WebServerFactoryCustomizer.java:26

  • Beware: calls to this interface are usually made from a
* WebServerFactoryCustomizerBeanPostProcessor which is a BeanPostProcessor (so called
* very early in the ApplicationContext lifecycle). It might be safer to lookup dependencies
  • lazily in the enclosing BeanFactory rather than injecting them with @Autowired.

框架⾃⼰写"It might be safer to ... rather than injecting them with @Autowired "——⼀个以依赖注⼊为⽴身之本的框架,在这⾥劝你别⽤依赖注⼊。这句话本身就是三明治时序的另⼀张账单。

⼋、Actuator:⼀扇只肯开⼀条缝的体检窗⼝后半章换个⽅向。⻔市开起来了,货也能出了,可运维要问:这坊⾥现在到底什么状况?

Actuator 就是坊⾥的体检窗⼝。它的设计第⼀性原理,写在 @Endpoint 的类 javadoc ⾥,⼀句话:

// [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/Endpoint.java:39(javadoc)

* {@code @Endpoint} represents the lowest common denominator for endpoints and
  • intentionally limits the sorts of operation methods that may be defined in order to
  • support the broadest possible range of exposure technologies.
"lowest common denominator"——最⼩公倍数,⽽且是 intentionally limits (刻意限制)。

所以⼀个端点只能有三种操作: @ReadOperation 、 @WriteOperation 、 @DeleteOperation ,外加可选的 @Selector 参数。为什么这么抠?因为这三件事在 HTTP、JMX、Jersey ⾥都能表达。多⼀种,就有⼀种技术表达不了。

代价直接写在映射表上:

// [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/web/annotation/RequestPredicateFactory.java:142

private WebEndpointHttpMethod determineHttpMethod(OperationType operationType) {
if (operationType == OperationType.WRITE) { return WebEndpointHttpMethod.POST; }
if (operationType == OperationType.DELETE) { return WebEndpointHttpMethod.DELETE; }
return WebEndpointHttpMethod.GET;
}

READ → GET,WRITE → POST(不是 PUT!),DELETE → DELETE。 没有 PUT,没有 PATCH。⼀个改⽇志级别的操作和⼀个新建资源的操作,在 Actuator 眼⾥都是 POST 。这不是疏漏,是"最⼩公倍数"的必然结果——JMX ⾥没有 PUT 这回事。

⼀个抽象层为了兼容最弱的那个后端,把最强的那个后端也削平了。这是所有"统⼀抽象"逃不掉的税。

九、借⼒不借形:⼀个把⾃⼰的招牌全砸了的 HandlerMappingActuator 的端点最终要变成 HTTP 路由。Boot 的做法是本章第⼆精妙的⼀处。

// [boot] module/spring-boot-webmvc/src/main/java/org/springframework/boot/webmvc/actuate/endpoint/web/AbstractWebMvcEndpointHandlerMapping.java:91public abstract class AbstractWebMvcEndpointHandlerMapping extends RequestMappingInfoHandlerMapping它继承了 Spring MVC 的 RequestMappingInfoHandlerMapping ——那个负责扫 @RequestMapping 、建路由表、做内容协商、绑参数的主⼒。然后,它把两个"按注解扫描"的钩⼦全部关掉:

//同⽂件 :272@Override

protected boolean isHandler(Class<?> beanType) {
return false;
}

//同⽂件 :277@Override

protected @Nullable RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
return null;
}

isHandler 恒 false (没有任何 bean 算 handler), getMappingForMethod 恒 null (没有任何⽅法能推出映射)。⽗类那套注解驱动的机器,被彻底掐死。

然后⾃⼰⼿⼯建表:

//同⽂件 :165@Override

protected void initHandlerMethods() {
for (ExposableWebEndpoint endpoint : this.endpoints) {
for (WebOperation operation : endpoint.getOperations()) {
registerMappingForOperation(endpoint, operation);
}
}
if (this.shouldRegisterLinksMapping) {
registerLinksMapping();
}
}

它复⽤了 Spring MVC 的整套请求匹配、参数绑定、内容协商机器,却完全不⽤ @RequestMapping 驱动。 借⼒,不借形。

这样做的好处是实打实的: /actuator/** 那些路由不会污染业务的 @RequestMapping 命名空间,不会被业务的 @ControllerAdvice 误伤(它们在另⼀个 HandlerMapping ⾥),⽽ Accept 协商、路径变量解析这些复杂逻辑⼀⾏都不⽤重写。

🦴 每个 operation ⼀个 handler 实例,但 handler method 是同⼀个。 每个 WebOperation 被包成⼀个 OperationHandler 实例,⽽反射调⽤的那个 handle ⽅法是全局唯

⼀、缓存在 this.handleMethod ⾥的。所以 MVC 看到的是"⼀百个不同的 handler 对象,共⽤⼀个⽅法"——完全合法,只是很少有⼈这么⽤。

🦴 返回 null 会发⽣什么?

//同⽂件 :421

private @Nullable Object handleResult(@Nullable Object result, HttpMethod httpMethod) {
if (result == null) {
return new ResponseEntity<>(
(httpMethod != HttpMethod.GET) ? HttpStatus.NO_CONTENT : HttpStatus.NOT_FOUND);
}

...

}

GET 返回 null → 404;⾮ GET 返回 null → 204。 你访问 /actuator/health/⼀个不存在的组 拿到 404,就是这⼀⾏。

⼗、三重⻔:⼀个端点要过三关才能被你摸到这是 Actuator 最容易配错的地⽅,也是本章最需要回源核实的⼀段。因为它关乎安全。

第⼀关:exposure(露不露脸)

// [boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/EndpointExposure.java:25

public enum EndpointExposure {

/** Exposed over a JMX endpoint. */

JMX("health"),

/** Exposed over a web endpoint. */

WEB("health");
private final String[] defaultIncludes;

...

}

⭐ 本基线的默认暴露集合,WEB 和 JMX 都是 {"health"} ,只此⼀个。既没有 info ,更没有 * 。

⽂档独⽴佐证( [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/actuator/endpoints.adoc:171 ):

By default, only the health endpoint is exposed over HTTP and JMX.Since Endpoints may contain sensitive information, you should carefully consider when to expose them.请把这条钉在墙上: info 端点在 Boot 2.x 时代是默认暴露的,本基线不是。 ⽹上⼤量⽂章还在说"默认暴露 health 和 info",别照抄。

匹配逻辑三⾏,但有个陷阱:

// [boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/expose/IncludeExcludeEndpointFilter.java:125

public final boolean match(EndpointId endpointId) {
return isIncluded(endpointId) && !isExcluded(endpointId);
}
private boolean isIncluded(EndpointId endpointId) {
if (this.include.isEmpty()) { return this.defaultIncludes.matches(endpointId); }
return this.include.matches(endpointId);
}

⚠ ⼀旦你显式配了 include ,默认值整个失效——是替换,不是叠加。 也就是说 management.endpoints.web.exposure.include=metrics 会顺⼿把 health 关掉。这是线上

事故的常⻅配⽅:上线前加了个 metrics,第⼆天 k8s 的 readiness 探针全红。

第⼆关:access(能做到什么程度)

Access 枚举( [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Access.java:32 , @since 3.4.0 )三档: NONE <
READ_ONLY < UNRESTRICTED 。默认是 UNRESTRICTED ( Endpoint.java:71 ),解析优先级是: management.endpoint.<id>.access →

management.endpoints.access.default → 注解上的 defaultAccess ,最后统⼀被 management.endpoints.access.max-permitted 封顶。

⽣效⽅式是 operation 级过滤:

// [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/OperationFilter.java:45

static <O extends Operation> OperationFilter<O> byAccess(EndpointAccessResolver accessResolver) {
return (operation, endpointId, defaultAccess) -> {
Access access = accessResolver.accessFor(endpointId, defaultAccess);
return switch (access) {
case NONE -> false;
case READ_ONLY -> operation.getType() == OperationType.READ;
case UNRESTRICTED -> true;
};
};
}

全仓翻下来,唯⼀⼀个⾃带⾮默认 access 的内置端点是 shutdown:

// [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/ShutdownEndpoint.java:39

@Endpoint(id = "shutdown", defaultAccess = Access.NONE)

框架敢把默认 access 设成 UNRESTRICTED ,唯独对"能把进程关掉"这⼀个端点单独上锁。

第三关:isInvocable(还剩不剩操作)

// [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/annotation/EndpointDiscoverer.java:223

protected boolean isInvocable(E endpoint) {
return !endpoint.getOperations().isEmpty();
}

看起来⽆害,后果很硬:

⚠ 如果你配了 management.endpoints.access.default=read-only ,⼀个只有 @WriteOperation 的端点(⽐如 shutdown、loggers 的写那半)所有操作被 access 过滤光

→ operations 为空 → 整个端点被丢弃。 不是 405 Method Not Allowed,不是 403,是根本不存在,连 404 都是因为路由没建。

三关串起来:exposure(露脸)× access(权限)× isInvocable(还剩事可做)。 三扇⻔都开着,你才摸得到那个 URL。

🦴 还有⼀个隐藏的默认值会让你的调试⾛弯路: 判定 exposure 时,JMX 那⼀路根本不参与:

// [boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/endpoint/condition/OnAvailableEndpointCondition.java:165

contributors.add(new StandardExposureOutcomeContributor(environment, EndpointExposure.WEB));
if (environment.getProperty(JMX_ENABLED_KEY, Boolean.class, false)) {
contributors.add(new StandardExposureOutcomeContributor(environment, EndpointExposure.JMX));
}

spring.jmx.enabled 默认 false。所以 management.endpoints.jmx.exposure.include 你配了也⽩配,除⾮先把 JMX 打开。

端点各⾃能看到什么(都回源)

health —— [boot] module/spring-boot-health/src/main/java/org/springframework/boot/health/actuate/endpoint/HealthEndpoint.java:46 。⭐ 直

接调⽤和⾛ HTTP 是两套⾏为: 端点⾃⼰的私有⽅法 health(...) (同⽂件 :79 )传 getResult(apiVersion, null, SecurityContext.NONE, true, path) ,那个
true 是 showAll——JMX / 编程式调⽤看到的永远是全量细节。⽽ HealthEndpointWebExtension 的两个 @ReadOperation 都传 false ( [boot]
module/spring-boot-health/.../HealthEndpointWebExtension.java:70 ),才⾛ show-details 判定。这条差异很隐蔽,但它意味着"我把 show-details 关了"并不等
于"细节泄不出去"。 状态码只有两档: DOWN 和 OUT_OF_SERVICE → 503,其余(含 UNKNOWN )→ 200( [boot] module/spring-boot-
health/.../SimpleHttpCodeStatusMapper.java:47 )。聚合顺序 DEFAULT_ORDER = List.of(DOWN, OUT_OF_SERVICE, UP, UNKNOWN) ( [boot] module/spring-
boot-health/src/main/java/org/springframework/boot/health/contributor/Status.java:69 ),取最⼩——"⼀个 DOWN 全盘 DOWN"就是从这⾏来的。 默认
management.endpoint.health.show-details = NEVER ( [boot] module/spring-boot-health/.../HealthEndpointProperties.java:43 )。

beans ——沿 parent 链⼀路往上爬,每个上下⽂⼀条记录。过滤规则两条:

java // [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/beans/BeansEndpoint.java:144 private static boolean

isBeanEligible(String beanName, BeanDefinition bd, ConfigurableBeanFactory bf) { return (bd.getRole() != BeanDefinition.ROLE_INFRASTRUCTURE &&
(!bd.isLazyInit() || bf.containsSingleton(beanName))); }

⚠ ROLE_INFRASTRUCTURE 的基础设施 bean 不显示;懒加载且尚未实例化的 bean 也不显示。 这就是"我明明定义了这个 bean, /actuator/beans ⾥却找不到"的答案——不是

没造,是没资格上榜。

conditions —— [boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/condition/ConditionsReportEndpoint.java:55 。每个上下⽂输出四块: positiveMatches / negativeMatches / exclusions / unconditionalClasses 。这是第四⼗章说的"⾃动配置魔法难调试"的唯⼀正经解药:为什么这个 bean没⽣效,别猜,来这⼉看。注意它住在 spring-boot-actuator-autoconfigure ⽽不是 spring-boot-actuator ——因为它依赖 ConditionEvaluationReport ,是⾃动配置体系的产物。

env ——两个 @ReadOperation :带 pattern (Java 正则,写错抛 400)的全量查,和 @Selector 单条查。只输出 EnumerablePropertySource ——不可枚举的属性源在这⾥根本不出现。默认 show-values = NEVER 。⽽脱敏的默认⾏为是全遮,不是按关键词遮:

java // [boot] module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/Sanitizer.java:68 public @Nullable Object

sanitize(SanitizableData data, boolean showUnsanitized) { Object value = data.getValue(); if (value == null) { return null; } if
(!showUnsanitized) { return SanitizableData.SANITIZED_VALUE; } for (SanitizingFunction sanitizingFunction : this.sanitizingFunctions) { ... }
return value; }

SANITIZED_VALUE 就是 "****" 。 Sanitizer ⾃⼰不带任何默认关键词列表——所以默认配置下 /actuator/env 的每⼀个值都是 **** ,包括 java.version 。想看真值必须显式配 show-values 。这个默认很粗暴,但⽅向是对的:宁可全遮到没法⽤,不可漏⼀个密码。

metrics —— [boot] module/spring-boot-micrometer-metrics/src/main/java/org/springframework/boot/micrometer/metrics/actuate/endpoint/MetricsEndpoint.java:50 。 GET /actuator/metrics 只列名

字, GET /actuator/metrics/{name}?tag=k:v 才出数。对 CompositeMeterRegistry 会递归下钻。

安全那侧,默认规则⼀句话:

// [boot] module/spring-boot-security/src/main/java/org/springframework/boot/security/autoconfigure/actuate/web/servlet/ManagementWebSecurityAutoConfiguration.java:62(⽚段)

requests.requestMatchers(healthMatcher(), additionalHealthPathsMatcher()).permitAll();
requests.anyRequest().authenticated();

只有 health(及其 additional paths)匿名可访问,其余⼀律要认证。 但请留意类 javadoc 的 back-off 声明:你⼀旦⾃⼰定义了 SecurityFilterChain bean,这整块配置会完全退让,所有规则都得你⾃⼰写。 很多"Actuator 裸奔"事故的根因就在这⾥——不是 Boot 没保护,是你写了个⾃定义 chain 把保护顶掉了,⽽且没有任何警告。

⼗⼀、压轴:同⼀套机器,在⼀个进程⾥跑两遍最后⼀件事,把前后两半章缝在⼀起。

管理端⼝三态,由⼀个静态⽅法判定:

// [boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementPortType.java:55

public static ManagementPortType get(Environment environment) {
Integer managementPort = getPortProperty(environment, "management.server.");
if (managementPort != null && managementPort < 0) { return DISABLED; }
Integer serverPort = getPortProperty(environment, "server.");
return ((managementPort == null || (serverPort == null && managementPort.equals(8080))
|| (managementPort != 0 && managementPort.equals(serverPort))) ? SAME : DIFFERENT);
}

⚠ 注意那个 managementPort != 0 : management.server.port=0 永远算 DIFFERENT,哪怕 server.port 也是 0。你以为只是"随便给个端⼝",实际上会真的起两台

Tomcat。

DIFFERENT 分⽀⼲的事,才是本章的圆环:

// [boot] module/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ChildManagementContextInitializer.java:83(⽚段)

@Override

public void start() {
if (!(this.parentContext instanceof WebServerApplicationContext)) { return; }
ConfigurableApplicationContext managementContext = this.managementContext;
if (managementContext == null) {
managementContext = createManagementContext();
registerBeans(managementContext);
managementContext.refresh(); // ←在⽗上下⽂的 Lifecycle.start()⾥,refresh⼀个全新的上下⽂
this.managementContext = managementContext;
}
else { managementContext.start(); }
}

在⼀个上下⽂的⽣命周期回调⾥,refresh 出另⼀个完整的上下⽂。 ⽽ Tomcat 那侧提供的⼯⼚告诉你,⼦上下⽂是什么类型:

// [boot] module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/autoconfigure/actuate/web/server/TomcatServletManagementContextAutoConfiguration.java:44(⽚段)

@Bean

static ManagementContextFactory servletWebChildContextFactory() {
return new ManagementContextFactory(WebApplicationType.SERVLET, ServletWebServerFactory.class,
TomcatWebServerConfiguration.class, TomcatServletWebServerAutoConfiguration.class);
}

⭐ ⼦上下⽂也是⼀个 ServletWebServerApplicationContext ,也⾛⼀遍第⼀到第五节的全部流程:找⼯⼚ → 造 Tomcat → 三⼿障眼法 → 两个 Lifecycle → 绑端⼝。同⼀套"应⽤启动容器"的机器,在⼀个 JVM ⾥跑了两遍。

现在回头看第⼀节那句注释—— // Use bean names so that we don't consider the hierarchy 。如果 getWebServerFactory() 看⽗上下⽂,⼦上下⽂会找到⽗的那个⼯⼚ bean,于是两个上下⽂共⽤⼀台 Tomcat,管理端⼝独⽴就成了空话。 那句看似洁癖的注释,是这整个能⼒的地基。

⽽ phase 那侧的算术也终于收⼝:

// [boot] module/spring-boot-actuator-autoconfigure/.../web/server/ChildManagementContextInitializer.java:120@Override

public int getPhase() {
return WebServerApplicationContext.GRACEFUL_SHUTDOWN_PHASE - 512;
}

MAX − 1536 ,不多不少,正好卡在 START_STOP (MAX−2048)和 GRACEFUL (MAX−1024)中间。 于是:主服务器先起 → 管理上下⽂再起;停机时管理上下⽂先停 → 主服务器的优雅停机后停。那个 -512 不是随⼿写的,是算过的。

✨ ⽽更有意思的是两处相反的策略: getWebServerFactory() 只看当前上下⽂, WebServerFactoryCustomizerBeanPostProcessor 只看当前上下⽂,但——

// [boot] module/spring-boot-actuator/.../endpoint/annotation/EndpointDiscoverer.java(createEndpointBeans中)

BeanFactoryUtils.beanNamesForAnnotationIncludingAncestors(applicationContext, Endpoint.class)

IncludingAncestors ——端点发现要看⽗上下⽂。 ⼀个坚决不看,⼀个坚决要看,都是刻意的:前者为了让⼦上下⽂有⾃⼰的容器,后者为了让⼦上下⽂能看到你在主上下⽂⾥定义的 @Endpoint 。两条相反的规则,服务于同⼀个⽬标。

这种地⽅最能看出⼀个框架是不是被认真想过。

🦴 ⻣灰级细节汇总

1. ServletWebServerApplicationContext.refresh() 是 final 的( [boot] .../servlet/context/ServletWebServerApplicationContext.java:141 ),⽽且带兜

底清理:refresh 后半段抛异常时,⼿⼯ webServer.stop() + destroy() ,并⽤ addSuppressed 保证清理失败不吞掉原始异常。为什么必须这么做? 因为 Framework 的

AbstractApplicationContext 失败时只 destroyBeans() ( [framework] .../AbstractApplicationContext.java:645 ),⽽ WebServer 不是 bean,不会被销毁

——端⼝会泄漏。这段代码就是"把⾮ bean 资源塞进 bean 容器⽣命周期"的账单。

2. doClose() 的顺序是刻意的(同⽂件 :172 ):先发 AvailabilityChangeEvent.publish(this, ReadinessState.REFUSING_TRAFFIC) ,然后才 super.doClose() 。

先让 k8s 的 readiness 探针变红、让 Service 摘掉⾃⼰,再开始关。顺序反了,停机期间就会有请求打进来。

  1. Tomcat 的优雅停机是轮询,不是事件驱动。 GracefulShutdown 每 50ms 问⼀次"还有活⼉吗",判据是 getInProgressAsyncCount() > 0 或任⼀
StandardWrapper.getCountAllocated() > 0 ( [boot] module/spring-boot-
tomcat/src/main/java/org/springframework/boot/tomcat/GracefulShutdown.java )。⽽ Jetty 是往 handler 链上包⼀层⾃带的 GracefulHandler ( [boot]
module/spring-boot-jetty/.../servlet/JettyServletWebServerFactory.java:185 附近)。同⼀个接⼝⽅法,两种完全不同的实现路数。
4. WebServerFactory 是个空接⼝( [boot] module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/WebServerFactory.java ),

⼀个⽅法都没有。它存在的唯⼀意义,是给 WebServerFactoryCustomizerBeanPostProcessor ⼀个 instanceof 的抓⼿。

5. WebServer#shutDownGracefully 的默认实现是"⽴刻回调 IMMEDIATE"( [boot] .../server/WebServer.java ,标 @since 2.3.0 )——第三⽅实现不写这个⽅法也

能编译,只是不优雅。典型的"接⼝演进靠 default ⽅法"。

6. Actuator 的操作缓存 key 是三元组 (ApiVersion, Principal, WebServerNamespace) ( [boot] module/spring-boot-
actuator/.../endpoint/invoker/cache/CachingOperationInvoker.java )。把 principal 放进 key,是为了避免"A ⽤户的 show-details 结果被 B ⽤户读到"这种越权

缓存。⽽且没有默认 TTL——不配 management.endpoint.<id>.cache.time-to-live 就根本不缓存。

7. 默认媒体类型是 v3。 EndpointMediaTypes.DEFAULT 依次是 application/vnd.spring-boot.actuator.v3+json 、 v2+json 、 application/json ( [boot]
module/spring-boot-actuator/.../endpoint/web/EndpointMediaTypes.java:37 )。

⚠ 暗礁清单

  1. Filter bean 在 refresh 中途被提前实例化,连带依赖也被提前造——逃⽣舱是 DelegatingFilterProxyRegistrationBean + @Lazy 。
  1. 定义任何 ServletContextInitializer bean,会关掉所有 Servlet/Filter 的⾃动注册。
  1. management.endpoints.web.exposure.include 是替换不是叠加,配了 metrics 会顺⼿关掉 health。
  1. server.shutdown 本基线默认已是 GRACEFUL ,照抄旧⽂章会说反。
  1. /actuator/env 默认每个值都是 ****** ,连⾮敏感的也遮。
6. health 直接调⽤永远全量细节( showAll=true ),只有⾛ HTTP 才受 show-details 约束。
  1. beans 端点看不到 infrastructure bean 和未实例化的 lazy bean。
  1. access=read-only 会让纯写端点整个消失,不是 405,是不存在。
  1. 多个 ServletWebServerFactory bean 直接启动失败,不是取第⼀个。
10. management.server.port=0 永远算 DIFFERENT,会真的起两台服务器。
  1. management.server.ssl / management.server.address 在 SAME 模式下会 Assert 失败,不是静默忽略——错误信息是 "Management-specific SSL cannot beconfigured as the management server is not listening on a separate port" 。
  1. ⾃定义 SecurityFilterChain 会让 ManagementWebSecurityAutoConfiguration 完全退让,Actuator 的默认保护随之消失,⽆任何警告。

🎯 三句带⾛

1. ServletWebServerApplicationContext 在 onRefresh() ⾥⽤ getBean() 取出唯⼀的 ServletWebServerFactory 造服务器,在 finishRefresh() ⾥才

start() 绑端⼝;两者之间隔着"所有单例被实例化"这⼀步,Filter 提前实例化、 ServletContext 不可靠这两个经典坑都由此⽽来。

2. Tomcat 的"paused"靠三招实现: bindOnInit=false 、在 START_EVENT ⾥把 Connector 从 Service 上摘⾛、 loadOnStartup 空实现; start() 时逐⼀还原。服

务器完整地活着,但没有⻔。

  1. 本基线默认只暴露 health ⼀个端点(WEB 与 JMX 皆是), info 不在其中;端点要过 exposure、access、isInvocable 三关才可达,⽽ include 是替换默认值不是叠加。

承上启下到这⾥,⻔市开起来了,体检窗⼝也⽀上了。但通篇下来,你数⼀数出现过多少个以 server. 、 management. 开头的东⻄—— server.port 、 server.shutdown 、spring.lifecycle.timeout-per-shutdown-phase 、 management.endpoints.web.exposure.include 、 management.endpoint.health.show-details 、spring.jmx.enabled ……每⼀个都是⼀根拉绳。拉⼀下,坊⾥某处的机器就换个转法。

可这些绳⼦到底从哪⼉垂下来的?同⼀个 server.port ,可以写在 application.yml ⾥、写成 --server.port=9090 命令⾏参数、塞进 SERVER_PORT 环境变量、放进 k8s的 ConfigMap、或者由某个 profile 覆盖——它们同时存在时,谁说了算?

ServerProperties 那个字段声明成 @Nullable Integer ⽽不是 int ,不是随⼿写的:它要能表达"你根本没配",好把决定权让回给⼯⼚的裸默认 8080 。"没配"和"配成 0"是两件完全不同的事,⽽承载这个区别的那套机器,我们还⼀次都没打开过。

下⼀章,我们把绳⼦的另⼀头拽上来,看 Boot 的外部化配置: Environment 与 PropertySource 的层级、优先级到底怎么排、 @ConfigurationProperties 如何把⼀堆字符串松散地绑成⼀个强类型对象、以及 relaxed binding 那套"你怎么写它都认"的宽容,是怎么在源码⾥落地的。