第41章 卷十二 · 看料下单 · 一张清单就是一个 starter
⼀张清单就是⼀个 starter「我这⼀⽣没有造过⼀件器。 我只是⼀张纸,上⾯写着:要办成这件事,你得先把这⼏样料备⻬。 然后我就被⼈从箱⼦⾥剔了出去。」 —— spring-boot-starter-data-jpa 的⾃⽩⼀、把料包拆开,⾥⾯是空的我在成器坊的库房⾥⼲过⼀件很蠢的事。
我想弄明⽩ spring-boot-starter-data-jpa 到底"做"了什么,于是我做了每个源码解剖师都会做的第⼀件事:找到它的⽬录,进去, ls 。
$ ls -a starter/spring-boot-starter/. .. build.gradle$ ls -a starter/spring-boot-starter-webmvc/. .. build.gradle没有 src/ 。没有⼀个 .java 。没有⼀⾏代码。
这不是个别现象。本基线的 starter/ ⽬录下共 175 个⼦⽬录,其中 174 个是真 starter(判据是 build.gradle ⾥应⽤了 id "org.springframework.boot.starter" 这个插件)——没有⼀个有 src/ ⽬录。
我们花了整整⼀卷去追"⾃动配置是怎么魔法般⽣效的",⽽全世界的 Spring Boot 教程开篇教你写的那⼀⾏ <artifactId>spring-boot-starter-web</artifactId> ,它本身⼀个字节的逻辑都没有。
这就是本章要拆的反差:你以为你引⼊了⼀台机器,其实你只是交上去⼀张购物清单。
按本书的坊⾥话说:starter 是配好的料包——⽽料包⾥,往往⼀件成品也没有,只有⼀张写好的清单。
⼆、九⾏有效代码,全是 api先看最核⼼的那⼀个, spring-boot-starter 本尊。去掉 16 ⾏ Apache 协议头之后,全⽂如下:
// [boot] starter/spring-boot-starter/build.gradle:17-30
plugins {id "org.springframework.boot.starter"
}
description = "Core starter, including auto-configuration support, logging and YAML"
dependencies {
api(project(":starter:spring-boot-starter-logging"))
api(project(":core:spring-boot-autoconfigure"))
api("jakarta.annotation:jakarta.annotation-api")
api("org.yaml:snakeyaml")
}做了什么:声明"⽤ Spring Boot,你⾄少要有⽇志、⾃动配置内核、 jakarta.annotation 、SnakeYAML 这四样"。
为什么这么设计——三个观察,每⼀个都不是废话:


其⼀,全部是 api(...) ,⼀个 implementation(...) 都没有。 这在别的⼯程⾥会被 code review 骂死( api 会让依赖泄漏到下游),但在这⾥它是唯⼀正确的选择。
starter 的全部价值 100% 在传递性上:如果写成 implementation ,传递链⼀断,你引了 starter 却什么都拿不到,这个构件⽴刻变成⼀个纯粹的空壳。⼀个模块的依赖语义,被它的定位倒过来决定了。
其⼆,所有坐标都不写版本号。 api("org.yaml:snakeyaml") 后⾯没有 :2.6 。版本从哪来?下⼀节讲 BOM。
其三, description 不是注释。 它是会被读出去、进构件元数据、并且⾃动⽣成官⽅参考⽂档⾥那三张 starter 表格的字段( [boot]buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java )。写错了,⽂档就错了,⽽且没有任何编译器会拦你。 description 在这个⼯程⾥从"注释"升格成了"接⼝" ——后⾯我会说这件事的代价。
再看两个更典型的,它们暴露出 starter 依赖的两类:
// [boot] starter/spring-boot-starter-data-jpa/build.gradle:23-29
dependencies {
api(project(":starter:spring-boot-starter")) //横向:组合别的 starter
api(project(":starter:spring-boot-starter-jdbc"))
api(project(":module:spring-boot-data-jpa")) //纵向:拉进真正有代码的模块
api(project(":module:spring-boot-jdbc"))
}:starter:* 是横向组合, :module:* 是纵向落地。⾃动配置的代码住在 module/ 层,从来不住在 starter/ 层。 本基线 module/ 下有 130 个模块,其中 96 个带着AutoConfiguration.imports ⽂件,合计 309 条⾃动配置类;⽽ core/spring-boot-autoconfigure ⾃⼰那份 .imports 只剩 12 ⾏(admin / aop / availability /context×4 / info / jmx / ssl / task×2)。
本基线如此:Boot 3 时代绝⼤多数⾃动配置类挤在⼀个巨⼤的 spring-boot-autoconfigure jar ⾥,包名形如org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration 。Boot 4 把它们全搬进了 module/ ,包名也翻了个个⼉——现在是org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfiguration ( [boot] module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/autoconfigure/DataSourceAutoConfiguration.java:62 ,该类 javadoc 标着 @since 4.0.0 )。不要照抄⽹上关于 Boot 3 包路径的⽂章。
三、jar 不是空的,但它注定要被扔掉"starter 没有代码"——那它产出的 jar 是不是空⽂件?
不是。看构建插件:
// [boot] buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java:52-56
public void apply(Project project) {
PluginContainer plugins = project.getPlugins();
plugins.apply(DeployedPlugin.class);
plugins.apply(JavaLibraryPlugin.class); // ←它仍然是个 java library,仍然产 jar
plugins.apply(ConventionsPlugin.class);它照样⾛完整的 Java 构建,照样打 jar,jar 的 META-INF/ ⾥照样有 LICENSE.txt 、 NOTICE.txt 和⼀份正经的 MANIFEST。⾥⾯只是没有任何 .class ,也没有任何META-INF/spring/*.imports 。 官⽅⽂档那句 "The starter is really an empty jar."( [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/developing-auto-configuration.adoc:354 )是从"没有代码"的意义上说的,不是⽂件系统意义上的空。
⽽ MANIFEST ⾥被塞了⼀条不起眼的属性:
// [boot] buildSrc/src/main/java/org/springframework/boot/build/starters/StarterPlugin.java:49, :101-107
private static final String JAR_TYPE = "dependencies-starter";...
private void configureJarManifest(Project project) {
project.getTasks().withType(Jar.class, (jar) -> project.afterEvaluate((evaluated) -> {
jar.manifest((manifest) -> {
Map<String, Object> attributes = new TreeMap<>();
attributes.put("Spring-Boot-Jar-Type", JAR_TYPE);这条属性是 starter 给⾃⼰写的死亡通知书。
打可执⾏ jar 的时候,两个打包插件都会读它,读到就把这个 jar 从 BOOT-INF/lib/ ⾥剔出去:
// [boot] build-plugin/spring-boot-maven-plugin/src/main/java/org/springframework/boot/maven/JarTypeFilter.java:37-38
private static final Set<String> EXCLUDED_JAR_TYPES = Collections.unmodifiableSet(
new HashSet<>(Arrays.asList("annotation-processor", "dependencies-starter", "development-tool")));// [boot] build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/JarTypeFileSpec.java:35
private static final Set<String> EXCLUDED_JAR_TYPES = Set.of("dependencies-starter", "development-tool");读法:你打出来的那只 fat jar ⾥, BOOT-INF/lib/ 下永远不会出现 spring-boot-starter-*.jar 。starter 是构建期的东⻄;到了运⾏期,它该带的⼈都已经带进来了,⾃⼰就可以退场了。像⼀个只负责把客⼈领进⻔的引路⼈,落座之后就没他的事。
⚠ 但请注意这两⾏代码的不⼀致:Maven 版排除三种 jar type,Gradle 版只排除两种,少了 annotation-processor 。这不是随⼿的疏漏——Gradle 有独⽴的
annotationProcessor configuration,注解处理器本来就不在 runtime classpath 上,所以不需要在打包时再滤⼀次。可它确实意味着同⼀个概念在两个插件⾥维护了两份、且内容不同的常量。哪天要加第四种 jar type,你得记得改两个地⽅,⽽且要想清楚该不该都改。这种"看起来对称、实际不对称"的地⽅,是维护者最容易漏的。
四、名字就是全部的价值
现在给你看本章最漂亮的⼀个证据。
对⽐ spring-boot-starter-logging 和 spring-boot-starter-logback 这两个构件的 build.gradle ,从第 17 ⾏到第 40 ⾏逐⾏ diff,唯⼀的差异是第 21 ⾏的description :
// [boot] starter/spring-boot-starter-logging/build.gradle:21
description = "Starter for logging default logging" // ←原⽂如此,官⽅⼿滑重复了⼀个词// [boot] starter/spring-boot-starter-logback/build.gradle:21
description = "Starter for logging using Logback"两者的依赖⼀字不差,都是这三条:
// [boot] starter/spring-boot-starter-logging/build.gradle:24-26
api("ch.qos.logback:logback-classic")
api("org.apache.logging.log4j:log4j-to-slf4j")
api("org.slf4j:jul-to-slf4j")两个内容完全相同的构件,为什么要发两份?
因为它们表达的意图不同。 -logging 说的是"给我默认的那套⽇志", -logback 说的是"我明确要 Logback"。今天默认的那套恰好就是 Logback;明天如果默认换了, -logging 会跟着变, -logback 不会。
⼀个构件的价值,可以 100% 来⾃它的名字。 这句话如果不落到这两个⽂件上,会像句鸡汤;落到这两个⽂件上,它就是⼯程事实。
顺着这个逻辑往下⾛,就到了本章的第⼆个主题——命名不是审美问题,是可寻址性问题。
4.1 官⽅前缀是为 IDE 补全设计的
All **official** starters follow a similar naming pattern; spring-boot-starter-*, where * is a particular type of application.This naming structure is intended to help when you need to find a starter.The Maven integration in many IDEs lets you search dependencies by name.For example, with the appropriate Eclipse or Spring Tools plugin installed, you can press ctrl-space in the POM editor and type "spring-boot-starter" for acomplete list.( [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/using/build-systems.adoc:124-127 )
设计动机被⽩纸⿊字写死在⽂档⾥了:统⼀前缀,是为了让 IDE 的补全能⼀次列全。 这是"为⼯具⽽设计的命名"的⼀个教科书案例——命名约定的收益⽅不是⼈的记忆⼒,是补全列表。
4.2 第三⽅为什么必须叫 xxx-spring-boot-starter这是所有写过⾃定义 starter 的⼈都被念叨过的⼀条规矩,但绝⼤多数⼈不知道理由。理由不在商标,在⼯程:
You should make sure to provide a proper namespace for your starter.Do not start your module names with spring-boot, even if you use a different Maven groupId.We may offer official support for the thing you auto-configure in the future.( [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/developing-auto-configuration.adoc:263-265 )
"我们将来可能也做⼀个同样的东⻄。"
注意那句 "even if you use a different Maven groupId " ——就算你的 groupId 完全不冲突,也别⽤ spring-boot 开头。因为⼈类是按 artifactId 认构件的,⼀旦官⽅哪天出了个同名的 spring-boot-starter-acme ,混淆的成本落在所有使⽤者身上,不落在你身上。
完整的规矩是四条(同⽂件 :267-271 ): - ⾃动配置模块叫 acme-spring-boot ; - starter 叫 acme-spring-boot-starter ; - 两个合成⼀个的话,⽤ starter 那个名字; - 测试专⽤的叫 acme-spring-boot-starter-test 。
这⾥有个值得诚实标注的点:本基线的官⽅建议是⾃动配置模块叫 acme-spring-boot ( :242 、 :268 ),⽽不是很多⼈印象⾥的 acme-spring-boot-autoconfigure 。这与 Boot 4 ⾃⼰把 spring-boot-autoconfigure 拆成 module/spring-boot-jdbc 这类命名完全⼀致——官⽅把⾃身重构的规范同步进了"教你写starter"的⽂档。但本仓是浅克隆、⽆ git 历史,我⽆法证明"这是改过的",只能说"本基线的⽂档如此写"。
4.3 官⽅⾃⼰承认破过这条规矩最有意思的是 starter/README.adoc 。这份⽂件⾥有⼀张近百条的社区 starter 名录,⽽名录之前⽴着⼀个警示框:
WARNING: While the reference documentation mentions that 3rd party starters should not start with spring-boot,some starters do as they were designed before this was clarified.( [boot] starter/README.adoc:18-21 )
名录⾥确实混着违规者,⽐如 https://github.com/hdiv/spring-boot-starter-hdiv ( :129 ),紧挨着的却是合规的 camel-spring-boot 、 mybatis-spring-boot 、okta-spring-boot 。
规矩是后来才⽴的,⽴之前的⼈不算违规;⽂档不删旧名录,⽽是加⼀个 WARNING 承认历史。 这⽐"我们从来都是对的"要诚实得多,也是任何⻓命项⽬都躲不掉的⼀课。
五、BOM:那个不写版本号的秘密现在回答第⼆节留下的问题: api("org.yaml:snakeyaml") 后⾯没有版本号,版本从哪来?
答案是 [boot] platform/spring-boot-dependencies/build.gradle ——⼀个 2996 ⾏的⽂件,⾥⾯是 197 个 library(...) 声明。典型的⼀条⻓这样:// [boot] platform/spring-boot-dependencies/build.gradle:34-38(节选)
library("ActiveMQ", "6.3.1") {
group("org.apache.activemq") {
modules = [ "activemq-console", "activemq-spring" ]
bom("activemq-bom")
}...
}5.1 全世界的 <xxx.version> 覆盖技巧,根⼦是这两⾏你⼀定在某篇博客⾥⻅过"在 pom 的 <properties> ⾥写 <snakeyaml.version>2.7</snakeyaml.version> 就能覆盖版本"这个技巧。这个属性名是怎么来的?不是约定俗成,是⼀⾏代码算出来的:
// [boot] buildSrc/src/main/java/org/springframework/boot/build/bom/Library.java:113-114
this.versionProperty = "Spring Boot".equals(name) ? null
: name.toLowerCase(Locale.ENGLISH).replace(' ', '-') + ".version";规则:库名转⼩写、空格换连字符、加后缀 .version 。
library("ActiveMQ", ...) → activemq.version
library("Spring Framework", ...) → spring-framework.version唯⼀的例外是 "Spring Boot" ⾃⼰,返回 null ——它没有 version property。因为它的版本就是 BOM ⾃⼰的版本,不该被你覆盖掉;真让你改了,整个依赖体系会⽴刻分裂。⼀个三元表达式,挡住了⼀整类灾难。
5.2 modules 与 bom 是两种强度BOM DSL ⾥的两个关键字,落地⽅式完全不同:
// [boot] buildSrc/src/main/java/org/springframework/boot/build/bom/BomExtension.java:197-210
private void addModule(...) {...
dependencies.getConstraints().add(JavaPlatformPlugin.API_CONFIGURATION_NAME, constraint);
}
private void addBomImport(...) {...
dependencies.add(JavaPlatformPlugin.API_CONFIGURATION_NAME, dependencies.platform(bomDependency));
dependencies.add(BomPlugin.API_ENFORCED_CONFIGURATION_NAME, dependencies.enforcedPlatform(bomDependency));
}modules = [...] → ⼀条 constraint(约束,发布成 <dependencyManagement> ⾥的⼀⾏,属于"建议")。
bom("xxx-bom") → 同时注册为 platform (建议)和 enforcedPlatform (强制)。Spring Framework ⾛的正是后⼀条强路:
// [boot] platform/spring-boot-dependencies/build.gradle:2584-2588
library("Spring Framework", "${springFrameworkVersion}") {
firstParty()
group("org.springframework") {
bom("spring-framework-bom")
}⽽ spring-framework-bom 在另⼀个仓⾥,是这样定义的:


// [framework] framework-bom/framework-bom.gradle:8-14
dependencies {
constraints {
parent.moduleProjects.sort { "$it.name" }.each {
api project(it.path)
}
}
}它没有⼀个⼿写的版本号——整张表是从⼯程列表⾃动⽣成的。 所以 spring-core 、 spring-beans 、 spring-web ……永远同版本,这件事不靠纪律,靠⼀个 each 循环。
于是完整的版本链是:
你的 pom
└─ import spring-boot-dependencies ← Boot 的 BOM(197 个 library)
├─ constraints:每个第三⽅ module ⼀条
└─ import spring-framework-bom ← platform + enforcedPlatform
└─ constraints:每个 Framework 模块,同版本
⚠ 两仓版本必须分清:本基线 [boot] gradle.properties:25 写的是 springFrameworkVersion=7.1.0-M1 ,⽽ [framework] gradle.properties:1 是 7.1.0-SNAPSHOT 。这不是同⼀个构件。 别写成"Boot 4.2 ⽤的就是 framework 仓⾥这份代码"。
5.3 拿到 BOM 的四条路,各有各的代价Maven 侧两条:
继承 spring-boot-starter-parent 。 它⾃⼰的 parent 被替换成了 spring-boot-dependencies ( [boot] starter/spring-boot-starter-parent/build.gradle:27-
32 ),顺带塞给你六个默认属性( :36-43 ): java.version=17 、 resource.delimiter=@ 、 maven.compiler.release=${java.version} 、两个 UTF-8 编码、
spring-boot.run.main-class=${start-class} 。java.version 默认是 17,不是 21、不是 25。回源核实过,别猜。
parent 还替你做了两件你多半没意识到的事:把 application*.yml|yaml|properties 开了资源过滤、并把 Maven 的占位符从 ${...} 改成 @...@ ( :47-64 )——因为${...} 是 Spring ⾃⼰的占位符语法,两套要是撞在⼀起,你会得到⼀个极难查的 bug。以及 maven-compiler-plugin 默认开 -parameters ( :118-120 ),这是@ConfigurationProperties 构造器绑定、 @PathVariable 省参数名能⼯作的前提。
不继承 parent,只 import BOM。 代价被⽂档写死了:拿得到依赖管理,拿不到 pluginManagement( repackage 得⾃⼰配);⽽且不能再靠改 property 覆盖版本,要覆盖必须把条⽬写在 spring-boot-dependencies 之前(Maven 的 dependencyManagement 是"先声明者胜")。
Gradle 侧也是两条: io.spring.dependency-management 插件(⽀持 property 覆盖),或 Gradle 原⽣ platform(构建更快)。Boot 的 Gradle 插件不会主动应⽤前者,只是"你要是应⽤了,我顺⼿帮你导 BOM":
// [boot] build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/DependencyManagementPluginAction.java:40
extension.imports((importsHandler) -> importsHandler.mavenBom(SpringBootPlugin.BOM_COORDINATES));⚠ ⾛原⽣ platform 有⼀条极易踩的限制:platform 只对声明它的那个 configuration(及其继承者)⽣效,不像 Maven 的 dependencyManagement 是整个 pom ⽣效。写在
implementation 上的 platform,管不住 annotationProcessor ——⽽ spring-boot-configuration-processor 恰恰就住在那⾥。
六、⾃⼰写⼀个 starter:⼀张能照做的清单好了,反差讲完,现在给结论。想给⾃⼰的技术 "acme" 做⼀个 starter,你要交的件如下。
件 0:两个模块(可选拆分)。 acme-spring-boot (代码)+ acme-spring-boot-starter (清单)。⽂档明说这个拆分不是必须的:有可选特性就拆,简单的话合成⼀个也⾏。Boot ⾃⼰是拆的: module/spring-boot-jdbc + starter/spring-boot-starter-jdbc 。
件 1:⾃动配置类,标 @AutoConfiguration 。
// [boot] module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/autoconfigure/DataSourceAutoConfiguration.java:57-62
@AutoConfiguration(before = DataSourceInitializationAutoConfiguration.class)
@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })
@ConditionalOnMissingBean(type = "io.r2dbc.spi.ConnectionFactory")
@EnableConfigurationProperties(DataSourceProperties.class)
@Import({ DataSourcePoolMetadataProvidersConfiguration.class, DataSourceCheckpointRestoreConfiguration.class })
public final class DataSourceAutoConfiguration {注意 @ConditionalOnMissingBean 那⾥⽤的是字符串 "io.r2dbc.spi.ConnectionFactory" ⽽不是 Class ——因为 R2DBC 可能根本不在 classpath 上。
🦴 ⽽ @AutoConfiguration 这个注解本身有⼀条硬约束:
// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfiguration.java:55-61
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)@Documented
@Configuration(proxyBeanMethods = false) // ←硬编码,不可改@AutoConfigureBefore@AutoConfigureAfter
public @interface AutoConfiguration {javadoc 也把话说死了( :37-38 ):"with the exception that proxyBeanMethods is always false "。这意味着⾃动配置类⾥ @Bean ⽅法互相调⽤不会⾛代理,会真的执⾏两遍。 你在⾃⼰的 @Configuration ⾥习以为常的"调⼀下另⼀个 @Bean ⽅法拿同⼀个实例",在 @AutoConfiguration ⾥是错的。(这个注解 @since 2.7.0 , :53 。)
件 2: META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 。
⼀⾏⼀个全限定类名,纯⽂本。真实样本( [boot] module/spring-boot-jdbc/src/main/resources/META-INF/spring/...imports ,9 ⾏):
org.springframework.boot.jdbc.autoconfigure.DataSourceAutoConfigurationorg.springframework.boot.jdbc.autoconfigure.DataSourceInitializationAutoConfiguration...这个路径不是硬编码的常量,是拼出来的:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/annotation/ImportCandidates.java:47, :84-85
private static final String LOCATION = "META-INF/spring/%s.imports";...
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);✨ "注解全限定名即命名空间" ——同⼀套加载机制因此能承载任意多种候选清单( AutoConfiguration.imports 、Actuator 的
ManagementContextConfiguration.imports ……)⽽互不⼲扰。⽐ spring.factories 那种"⼀个⽂件塞所有 key"的⽼办法可扩展得多,也更适合 GraalVM 的静态分析。
件 3: @ConfigurationProperties 类。 官⽅给的样板就叫 Acme:
// [boot] documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/features/developingautoconfiguration/customstarter/configurationkeys/AcmeProperties.java:23-34
@ConfigurationProperties("acme")
public class AcmeProperties {/**
- Whether to check the location of acme resources.
*/
private boolean checkLocation = true;/**
- Timeout for establishing a connection to the acme server.
*/
private Duration loginTimeout = Duration.ofSeconds(3);
由⾃动配置类⽤ @EnableConfigurationProperties(AcmeProperties.class) 激活。⽤你⾃⼰的命名空间,别⽤ server 、 management 、 spring 这些 Boot 占着的前缀——理由⽂档写得很直⽩:"we may modify these namespaces in the future in ways that break your modules"( :279 )。
那两段字段 javadoc 也不是注释,它们就是⽂档本身: spring-boot-configuration-processor 会把它们抓进 META-INF/spring-configuration-metadata.json ,IDE⾥悬停时弹出的那⾏说明就是它。官⽅甚⾄给了内部写作规范( :292-296 ):不要⽤ "The"/"A" 开头; boolean ⽤ "Whether"/"Enable" 开头;集合⽤ "Comma-separatedlist" 开头;⽤ Duration ⽽不是 long ;不要在描述⾥写默认值(默认值处理器⾃⼰会读)。上⾯那两条注释,恰好逐条命中。
件 4:条件注解。 @ConditionalOnClass / @ConditionalOnMissingBean / @ConditionalOnProperty 那⼀家⼦——这是"看料下单"的机制本体,ch38 已经拆过。这⾥只补两条写 starter 时必踩的坑,放在下⾯的暗礁⾥。
可选件: META-INF/additional-spring-configuration-metadata.json (描述处理器看不⻅的 key、标废弃)、 META-INF/spring.factories (⾃动配置搬⾛了,但FailureAnalyzer 、 ConnectionDetailsFactory 这些扩展点还在⽤它)、 META-INF/spring/aot.factories ( RuntimeHintsRegistrar )。
最后⼀条硬约束,别漏:
NOTE: Either way, your starter must reference the core Spring Boot starter (spring-boot-starter)
directly or indirectly (there is no need to add it if your starter relies on another starter).( [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/developing-auto-configuration.adoc:363-364 )
同⼀段还有⼀条常被违反的( :361 ):"you should not include optional dependencies." starter 是给"典型⽤法"备料的,不是把所有可能性都塞进去。Boot ⾃⼰怎么处理可选依赖?放在 module 层,⽤⼀个专⻔的 optional configuration ——它"是本⼯程编译和运⾏ classpath 的⼀部分,但不影响依赖⽅的 classpath"( [boot]buildSrc/src/main/java/org/springframework/boot/build/optional/OptionalDependenciesPlugin.java:27-31 )。所以 module/spring-boot-jdbc 敢把 Hikari、DBCP2、C3P0、Oracle UCP、Vibur ⼗⼏个连接池都拉进来编译,⽽不会污染你的⼯程。module 层负责"能⽀持什么",starter 层负责"默认给你哪⼀个"——两层职责,两种依赖语义。
🦴 ⻣灰级细节
⼀、starter 的分类不是⼈贴的标签,是从依赖图算出来的。 官⽅参考⽂档⾥那三张表(应⽤型 / ⽣产型 / 技术型),定义就在这三个⽅法⾥:
// [boot] buildSrc/src/main/java/org/springframework/boot/build/starters/DocumentStarters.java:141-152
private boolean isProduction() {
return this.name.equals("spring-boot-starter-actuator");
}
private boolean isTechnical() {
return !Arrays.asList("spring-boot-starter", "spring-boot-starter-test").contains(this.name)
&& !isProduction() && !this.dependencies.contains("spring-boot-starter");
}
private boolean isApplication() {
return !isProduction() && !isTechnical();
}两个观察:"⽣产型 starter"是⼀个硬编码的单元素集合,全世界只有 spring-boot-starter-actuator ⼀个;⽽"技术型"的判据是"解析后的依赖⾥不含 spring-boot-starter " ——也就是"不把 Boot 内核拖进来的 starter",它的⽤途是替换某个技术切⾯(换⽇志实现、换容器),⽽不是新增能⼒。分类永远和事实⼀致,你没法给⼀个实际拖进内核的 starter 贴"技术型"的标签。
(源码⾥静态可⻅的"不依赖任何其他 starter ⼯程"的有 6 个: logging 、 logback 、 log4j2 、 restdocs 、 tomcat-runtime 、 jetty-runtime 。但 isTechnical()⽤的是解析后的依赖,我没跑 Gradle 解析,所以别把这 6 个当成官⽅那张表的最终名单。)
⼆、Boot ⾃⼰有三道构建期守卫,你可以照抄去做⾃定义 starter 的 CI。 StarterPlugin.apply() 给每个 starter 挂了三个 check( :71-73 ):查类路径冲突、查多余的exclude 、查未被 BOM 约束的直接依赖。第三个的实现只有⼀句 removeAll :
// [boot] buildSrc/src/main/java/org/springframework/boot/build/classpath/CheckClasspathForUnconstrainedDirectDependencies.java:72-75
unconstrainedDependencies.removeAll(constraints);
if (!unconstrainedDependencies.isEmpty()) {
throw new GradleException("Found unconstrained direct dependencies: " + unconstrainedDependencies);
}在 Boot ⾃⼰的仓⾥,你不可能往 starter ⾥加⼀个 BOM 没管的依赖——构建直接失败。 这就是"starter ⾥的坐标从来不写版本号"这件事的制度保障。类似地, .imports ⽂件的三条规则也是构建期强制的( [boot] buildSrc/src/main/java/org/springframework/boot/build/autoconfigure/CheckAutoConfigurationImports.java:70-97 ):⾥⾯写的类必须找得到、必须真的标了 @AutoConfiguration 、条⽬必须按字⺟序排——不排序就失败,还贴⼼地把排好序的正确内容写到 build/.../sorted-
*.imports 让你去抄。
三、本基线三条反直觉的事实,都要标注"本基线如此"。 - spring-boot-starter-web 被废弃了。 [boot] starter/spring-boot-starter-web/build.gradle:21 的description 结尾赫然写着 (deprecated in favor of spring-boot-starter-webmvc) 。全世界最出名的那个 Spring Boot 构件,在这份主⼲快照⾥已经是弃⽤状态。同批被废的还有 4 个: web-services → webservices (少⼀个连字符)、三个 oauth2-* → security-oauth2-* 。Boot 3 不是这样。 - 没有 Undertow。 module/ 、starter/ 、BOM 三处全⽆踪迹。换容器的官⽅选项在这⾥只剩 Tomcat / Jetty / Reactor Netty。 - ⼀个 .replacements ⽂件都没有。 Boot 提供了⼀个机制叫 META-INF/spring/xxx.replacements ,⽤来在改包名/改类名时保持旧名可解析(实现在 [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfigurationReplacements.java:47 )。⽽ Boot 4 做了史上最⼤规模的⾃动配置类改包名, find . -name "*.replacements" 却返回 0。我只陈述这个事实,不替官⽅解释动机——仓⾥没有任何线索能⽀撑⼀个结论。
⚠ 暗礁
礁⼀:uber-jar 会静默毁掉 .imports 。 ImportCandidates.load() 靠 ClassLoader.getResources() 全 classpath 枚举( [boot] core/spring-boot/.../ImportCandidates.java:85 )——每个 jar ⼀份,全部收集。⼀旦你⽤ maven-shade-plugin 打 uber-jar ⽽没做合并,⼏⼗份同名⽂件会互相覆盖,只剩⼀份。
然后你会看到这句话:
// [boot] core/spring-boot-autoconfigure/.../AutoConfigurationImportSelector.java:205-208
Assert.state(!CollectionUtils.isEmpty(configurations),"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.");那句 "If you are using a custom packaging" 就是专⻔为踩这个坑的⼈写的。
⽽如果你继承了 spring-boot-starter-parent ,官⽅已经替你填好了这个坑—— [boot] starter/spring-boot-starter-parent/build.gradle:259-273 显式给 shade插件配了五个 transformer,合并 spring.handlers 、 spring.schemas 、 AutoConfiguration.imports 、 ManagementContextConfiguration.imports 和spring.factories 。⽤ parent 的⼈⼀辈⼦不会遇到这个坑;不⽤ parent 的⼈会遇到,⽽且极难查。 这是"默认值的价值"最完美的例证,也是"魔法的代价"最完美的例证——同⼀件事。
礁⼆: @ConditionalOnClass 直接标在 @Bean ⽅法上⽆效。 ⽂档说得很清楚:
This mechanism does not apply the same way to @Bean methods where typically the return type isthe target of the condition: before the condition on the method applies, the JVM will have loadedthe class and potentially processed method references which will fail if the class is not present.( [boot] .../developing-auto-configuration.adoc:103 )
根因: @ConditionalOnClass 之所以能写"不存在的类",全靠注解元数据由 ASM 读字节码解析、不加载类( :100 )。可 @Bean ⽅法的返回类型是⽅法签名的⼀部分,JVM绕不过去。解法是套⼀层内部 @Configuration 把条件隔离出去( [boot]documentation/.../conditionannotations/classconditions/MyAutoConfiguration.java:31-41 )。
同源的第⼆条:把 @ConditionalOnClass 做成组合元注解时,必须⽤ name ⽽不是 value ( :109 )。 before / after 同理,元注解场景要改⽤beforeName / afterName 。Boot 的构建检查 CheckAutoConfigurationClasses ( [boot] buildSrc/.../CheckAutoConfigurationClasses.java:159-207 )会双向强制这件事——该⽤ String 的地⽅⽤了 Class 会失败,反过来也会。
礁三:排序只管注册顺序,不管创建顺序。 @AutoConfigureBefore / @AutoConfigureAfter 影响的是 bean definition 的注册顺序,不是 bean 的创建顺序(后者由依赖关系和 @DependsOn 决定)。这是⾼频误解,栽在这⾥的⼈不少。
礁四(这条是给⽂档提的):官⽅⽂档⾃⼰已经跟不上这次改名了。 同⼀个⽂件 [boot] documentation/spring-boot-docs/src/docs/antora/modules/how-to/pages/webserver.adoc ,第 15 ⾏还在写 "the spring-boot-starter-web includes Tomcat by including spring-boot-starter-tomcat ",⽽第 32 ⾏的 Maven 示例⾥已经改⽤ spring-boot-starter-webmvc 了。同⼀⻚,前⾯⽤旧名,后⾯⽤新名。 这当然是主⼲快照的正常状态,但它精确地说明了⼀件事:当"名字"承载了全部语义(第四节),改名的成本就会渗透到每⼀处提到这个名字的散⽂⾥——⽽散⽂没有编译器。 description 升格成接⼝的那⼀刻,⽂档漂移也就升格成了 bug。
🎯 三句带⾛1. starter 没有代码,只有⼀张 api 依赖清单;它的 jar ⾥有 MANIFEST 却没有⼀个 .class ,MANIFEST ⾥那条 Spring-Boot-Jar-Type: dependencies-starter会让它在打包时被从 BOOT-INF/lib/ ⾥剔掉——它是构建期构件,运⾏期不存在。
2. 版本不归 starter 管,归 BOM 管: spring-boot-dependencies ⽤ 197 个 library(...) 声明⽣成 <dependencyManagement> ,覆盖⽤的 xxx.version 属性名由"库名转⼩写、空格换连字符、加 .version "算出( Spring Boot ⾃⼰没有该属性);Framework 那⼀层再由 spring-framework-bom 从⼯程列表⾃动⽣成,保证同版本。