源码小说CodeStory
登录
上一章

32,774 字 · 约 82 分钟

下一章
字体

主题

版式

第44章 卷十三 · 周边 · 外部化配置:@ConfigurationProperties 与 Profile

外部化配置:@ConfigurationProperties 与 Profile「我叫 first-name 。我也叫 firstName 。我还叫 FIRST_NAME 、 first_name 、 FIRST-NAME 。 可我只有⼀个 hashCode——因为算它的时候,短横线、下划线、⼤⼩写,全被扔掉了。」 —— ConfigurationPropertyName 的⾃⽩开场:⼀张料单,⼗⼏种写法成器坊⾥有⼀件很特殊的器。

别的器都是"照图纸下料、跟别的器榫卯扣合"造出来的。可这⼀件不是——它身上没有⼀处榫卯,它的每⼀个字段,都要从坊外递进来的⼀张料单上抄。料单可能是 jar ⾥的application.yml ,可能是运维在 K8s ConfigMap ⾥挂的⼀个⽂件,可能是启动脚本⾥ export 的⼀个环境变量,也可能是 java -jar 后⾯跟的那⼀串 -- 。

麻烦在于:同⼀味料,在不同的单⼦上写法完全不同。

application.properties my.main-project.person.first-name = Rod

application.yml my.mainProject.person.firstName: Rod

Linux 环境变量 MY_MAINPROJECT_PERSON_FIRSTNAME=Rod

Java 字段却只有⼀个名字: firstName 。

⽽ Spring Framework 的 Environment 只会做⼀件极朴素的事:拿着字符串 key,逐个 property source 精确 equals 地问⼀遍。

// [framework] spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java:73

protected <T> @Nullable T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) {
if (this.propertySources != null) {
for (PropertySource<?> propertySource : this.propertySources) {
Object value = propertySource.getProperty(key);
if (value != null) { ... return convertValueIfNecessary(value, targetValueType); }
}
}
return null;
}

⼀个 for 循环,第⼀个⾮ null 就赢。没有宽松,没有结构,没有嵌套。

于是 Boot 必须在中间插⼀层。这⼀章要拆的,就是这层的三块⻣头:

  1. 名字——怎么让⼗⼏种写法收敛成同⼀个身份;
  1. 结构——怎么把⼀堆扁平 key 塞进⼀个有嵌套、有 List 、有 Map 、还可能是不可变 record 的对象;
  1. 来源与优先级——命令⾏、环境变量、jar 内 yml、jar 外 profile ⽂件……到底谁盖谁。⽽且 profile 本身还是从配置⾥读出来的,这是个鸡⽣蛋。
Boot 把这三件事分给了三套机制: ConfigurationPropertyName (名字)、 Binder + DataObjectBinder (结构)、 ConfigDataEnvironment 的贡献者树(来源)。

顺带说个本基线的观察:⾃动配置那⼀⼤⽚在 Boot 4 ⾥被⼤搬家( module/ 、 core/ 、 starter/ 重组),⽽绑定这⼀块包名⼀动没动,仍是org.springframework.boot.context.properties[.bind|.source] 。地基不好挪。

⼀、名字:⼀个类回答"什么算同⼀个属性"

整个宽松绑定的⼼脏,是⼀个 1218 ⾏的类。它的 javadoc 就是规范本身:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java:34/**

  • A configuration property name composed of elements separated by dots. User created
  • names may contain the characters "a-z" "0-9" and "-", they must
  • be lower-case and must start with an alphanumeric character. The "-" is used
  • purely for formatting, i.e. "foo-bar" and "foobar" are considered equivalent.
  • ...
  • The "[" and "]" characters may be used to indicate an associative
* index (i.e. a Map key or a Collection index). Indexes names are not
  • restricted and are considered case-sensitive.

*/

四条硬规则,后⾯⼀切⾏为都从这⾥⻓出来:

⽤户写的规范名只能是⼩写字⺟、数字、短横线,且必须以字⺟数字开头;

短横线纯粹是排版, foo-bar 与 foobar 等价;

[...] ⾥的索引不受限、⼤⼩写敏感——这是 Map key 保真的唯⼀⼿段;

名字不能以 . 开头或结尾。

⼀个名字有三张脸( Form , :752 ): ORIGINAL 原样、 DASHED ⽤于 toString 、 UNIFORM ⽤于 equals / hashCode 。 UNIFORM 的规则是"⼩写 + 只保留字⺟数字",连短横线都不留。

为什么宽松绑定跑得动:hashCode 只喂 UNIFORM 字符// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java:922

int hashCode(int index) {
int hashCode = this.hashCode[index];
if (hashCode == 0) {
boolean indexed = getType(index).isIndexed();
int length = getLength(index);
for (int i = 0; i < length; i++) {
char ch = charAt(index, i);
if (!indexed) { ch = Character.toLowerCase(ch); }
if (ElementsParser.isAlphaNumeric(ch)) { // ←⾮字⺟数字直接跳过
hashCode = 31 * hashCode + ch;
}
}
this.hashCode[index] = hashCode;
}
return hashCode;
}

做了什么:算 hash 时先⼩写化,再把⼀切⾮字⺟数字的字符(短横线、下划线)直接跳过。索引段( [...] )例外,原样参与。

为什么这么设计:这⼀⾏ if (ElementsParser.isAlphaNumeric(ch)) ,让 foo-bar 、 fooBar 、 foo_bar 、 FOO_BAR 的 hashCode 天⽣相同。于是宽松匹配可以直接⽤

HashMap 建索引,⽽不必"拿着⽬标名去线性扫描每⼀个 key、逐个做模糊⽐对"。

这是整个⼦系统性能可接受的根本原因。宽松不是靠遍历换来的,是靠把"宽松"这件事塞进 hash 函数换来的。

equals 的三级快慢通道⽐较时也不是⽆脑归⼀化:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java:394

private boolean elementDiffers(Elements e1, Elements e2, int i) {
ElementType type1 = e1.getType(i);
ElementType type2 = e2.getType(i);
if (type1.allowsFastEqualityCheck() && type2.allowsFastEqualityCheck()) {
return !fastElementEquals(e1, e2, i); //逐字符硬⽐
}
if (type1.allowsDashIgnoringEqualityCheck() && type2.allowsDashIgnoringEqualityCheck()) {
return !dashIgnoringElementEquals(e1, e2, i); //⽐时跳过 '-'
}
return !defaultElementEquals(e1, e2, i); //⼩写化 +跳过⼀切⾮字⺟数字
}

ElementType 在解析时⼀次性判定——是纯⼩写的 UNIFORM 、带短横线的 DASHED 、含⼤写下划线的 NON_UNIFORM ,还是索引。所以"这次⽐较能⾛哪条通道"是 O(1) 决策,⼤多数真实场景(两边都是规范⼩写名)直接⾛最快那条。

⚠ 宽松的代价:尾巴上的垃圾被吃掉了

仓库⾥留着⼀串带 issue 号的回归测试,它们全是踩出来的:

// [boot] core/spring-boot/src/test/java/org/springframework/boot/context/properties/source/ConfigurationPropertyNameTests.java:715

ConfigurationPropertyName name1 = ConfigurationPropertyName.of("example.demo");
ConfigurationPropertyName name2 = ConfigurationPropertyName.adapt("example.demo$$", '.');

这两个名字在本基线⾥是相等的。 $$ 是"⾮字⺟数字",于是被 hashCode 跳过、被 defaultElementEquals 跳过,消失了。

同⼀个测试⽂件的上⽅还挂着⼀组: my.sources[0].xame ≠ my.sources[0].xamespace (gh-14665)、 example.mymap.ALPHA ≠ example.mymap.ALPHA_BRAVO (gh-
15152)、 auto-time-request ≠ auto-time-requests (gh-16855)。三个 issue 号,三次"宽松过头了"。

这就是我对这套设计的第⼀条质疑:宽松绑定不是免费的便利,它是⼀次刻意的信息丢失。 丢掉的信息⾥,⼤部分是⽆害的(⼤⼩写、短横线),但边界上必然出现"两个你认为不同的名字,系统认为相同"。Spring 团队⽤⼀串回归测试把边界⼀⼨⼀⼨钉住,这说明边界本身是含混的,⽽不是⾃明的。你在⾃定义 property source 或做配置迁移⼯具时,不能假设"名字不同 ⇒ 属性不同"。

of 严格, adapt 宽容——分⼯线在哪两个⼊⼝,两种脾⽓:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java:663

static @Nullable ConfigurationPropertyName of(@Nullable CharSequence name, boolean returnNullIfInvalid) {
Elements elements = elementsOf(name, returnNullIfInvalid, ElementsParser.DEFAULT_CAPACITY);
return (elements != null) ? new ConfigurationPropertyName(elements) : null;
}

elementsOf ( :674 )⾥那段判断很关键:只要有任何⼀个元素被判成 NON_UNIFORM (含⼤写、含下划线),要么返回 null ,要么直接抛InvalidConfigurationPropertyNameException 。

⽽ adapt ( :719 、 :736 )的 javadoc 明说⾃⼰"⽐ of 宽容,允许混合⼤⼩写和 _ ,其它⾮法字符在解析时被剥掉"。

分⼯: - 我们⾃⼰写的名字(注解⾥的 prefix 、 @Value ⾥的 key)⾛ of ——必须规范,写错⽴刻炸; - 外部来的名字(property source ⾥那些千奇百怪的 key)⾛ adapt ——怎么脏都得吞下去。

这条线直接解释了⼀个⾼频翻⻋现场:

@ConfigurationProperties(prefix = "myApp") 启动即失败。
因为绑定⼊⼝是 getBinder().bind(annotation.prefix(), target, bindHandler) ( [boot] core/spring-
boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java:96 ),最终落到 of 这条严格通道上。⽂档也把这条写成
了硬规定:「The prefix value for the annotationmust be in kebab case」( [boot] documentation/spring-boot-
docs/src/docs/antora/modules/reference/pages/features/external-config.adoc:1067 )。

注意这⾥的不对称:你的字段可以叫 firstName (驼峰),因为字段名会被 DataObjectPropertyName.toDashedForm 转成 first-name ;但你的 prefix 不可以,它必须你⾃⼰写成规范形。同⼀个注解上,两个名字⾛两套规矩——这个不对称在⽂档⾥只有⼀句 NOTE,在代码⾥则是 of 与 toDashedForm 两条完全不同的路径。

⼆、环境变量:⼀个名字,四个候选Linux shell 不允许变量名带点号,更不允许带短横线。所以环境变量这⼀路必须单独开⼀个映射器:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapper.java:47

public List<String> map(ConfigurationPropertyName configurationPropertyName) {
List<String> mapped = new ArrayList<>(4);
addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.SYSTEM_ENVIRONMENT, true));
addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.LEGACY_SYSTEM_ENVIRONMENT, true));
addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.SYSTEM_ENVIRONMENT, false));
addIfMissing(mapped, configurationPropertyName.toString(ToStringFormat.LEGACY_SYSTEM_ENVIRONMENT, false));
return mapped;
}

两种格式的差别只在⼀处——短横线怎么处理:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertyName.java:567

case SYSTEM_ENVIRONMENT -> buildSimpleToString('_', (i) -> getElement(i, Form.UNIFORM));
case LEGACY_SYSTEM_ENVIRONMENT -> buildSimpleToString('_', (i) -> getElement(i, Form.ORIGINAL).replace('-', '_'));

SYSTEM_ENVIRONMENT :点 → 下划线,短横线直接删掉;

LEGACY_SYSTEM_ENVIRONMENT :点 → 下划线,短横线 → 下划线。

再乘上"⼤写/⼩写"两种,共四个候选。单测把它钉死了:

// [boot] core/spring-boot/src/test/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapperTests.java:57

assertThat(mapConfigurationPropertyName("foo.the-bar"))
.containsExactly("FOO_THEBAR", "FOO_THE_BAR", "foo_thebar", "foo_the_bar");

🦴 ⻣灰级细节:官⽅⽂档只写了三条转换规则——「点换下划线 / 去掉短横线 / 转⼤写」,举的例⼦是 spring.main.log-startup-info →

SPRING_MAIN_LOGSTARTUPINFO ( [boot] .../external-config.adoc:1136-1140 ⼀带)。但从上⾯这⾏单测可以看到, SPRING_MAIN_LOG_STARTUP_INFO (legacy 形态)同样

能命中。

这是"读源码才知道"的⼀条。但我要给⼀句诚实的提醒:legacy 形态是兼容包袱,⽂档没有承诺它,别写进你的部署脚本当规范。 能读懂它,是为了在别⼈写成 _ 分隔时不⾄于怀疑⼈⽣;不是为了让你也这么写。

反向映射( String → Name )有⼀处硬规定:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SystemEnvironmentPropertyMapper.java:81

private CharSequence processElementValue(CharSequence value) {
String result = value.toString().toLowerCase(Locale.ENGLISH);
return isNumber(result) ? "[" + result + "]" : result; //纯数字段 →索引
}

⽆条件 toLowerCase ,纯数字段⾃动变成索引。于是有了这⼀串⾏为(全部来⾃单测 :39-47 ):

SERVER_PORT → server.portHOST_0 → host[0]HOST_0_NAME → host[0].nameHOST_F00_NAME → host.f00.name ← F00 是"F 零零",不是纯数字,不变索引

⚠ 暗礁:因为 toLowerCase 是⽆条件的,环境变量绑到 Map 时,key ⼀定是⼩写的。设 MY_PROPS_VALUES_KEY=VALUE ,你拿到的是 {"key"="VALUE"} ——名字被⼩写了,值没

有(⽂档 .../external-config.adoc:1157 ⼀带)。这条在 K8s ⾥配⼀堆动态 key 的场景下,能让⼈查半天。

⚠ 第⼆道暗礁,更隐蔽:不是所有环境变量样的源都享受这套规则。

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySource.java:181

private static boolean isSystemEnvironmentPropertySource(PropertySource<?> source) {
String name = source.getName();
return (source instanceof SystemEnvironmentPropertySource)
&& (StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME.equals(name)
|| name.endsWith("-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME));
}

必须类型是 SystemEnvironmentPropertySource ,且名字叫 systemEnvironment 或以 -systemEnvironment 结尾。你⾃⼰ addFirst ⼀个叫 myEnv 的MapPropertySource 塞满 FOO_BAR ⻛格的 key,⼀个也绑不上。⽂档同款表述在 .../external-config.adoc:1147 。判定条件写死成"看名字后缀",算不上优雅,但⾄少是明写在代码⾥的、可查的。

三、影⼦源:让 getProperty 也吃到宽松

宽松匹配这套本领,如果只服务 @ConfigurationProperties ,那 environment.getProperty("my.foo-bar") 就还是⽼⼀套精确匹配。Boot 的做法是往 Environment ⾥塞

⼀个影⼦源:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java:89

public static void attach(Environment environment) {
MutablePropertySources sources = ((ConfigurableEnvironment) environment).getPropertySources();
PropertySource<?> attached = getAttached(sources);
if (!isUsingSources(attached, sources)) {
attached = new ConfigurationPropertySourcesPropertySource(ATTACHED_PROPERTY_SOURCE_NAME,
new SpringConfigurationPropertySources(sources));
}
sources.remove(ATTACHED_PROPERTY_SOURCE_NAME);
sources.addFirst(attached); // ←插到最前
}

名字就叫 configurationProperties ( :47 )。它是⾃引⽤的:它被 addFirst 进 sources ,⽽它⾃⼰包着的⼜是同⼀个 sources 。防死循环靠⼀句过滤( :173 ):遍历时跳过StubPropertySource 和 ConfigurationPropertySourcesPropertySource ⾃⼰。

SpringApplication 调了两次 attach —— :355 与 :366 ,中间隔着 listeners.environmentPrepared(...) 。为什么要两次?因为中间那⼀步可能把 Environment 换

成另⼀个实例(⽐如 servlet 环境转换),换完得重挂。

真正把这层"接到 @Value 上"的,是 Boot ⾃⼰的 PropertyResolver :

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySourcesPropertyResolver.java:95

private @Nullable Object findPropertyValue(String key) {
ConfigurationPropertySourcesPropertySource attached = getAttached();
if (attached != null) {
ConfigurationPropertyName name = ConfigurationPropertyName.of(key, true); // ←注意 true
if (name != null) {
try {
ConfigurationProperty configurationProperty = attached.findConfigurationProperty(name);
return (configurationProperty != null) ? configurationProperty.getValue() : null;
}
catch (Exception ex) { /* Ignore */ }
}
}
return this.defaultResolver.getProperty(key, Object.class, false);
}
这⼀⾏ of(key, true) ,就是 @Value 与 @ConfigurationProperties 分家的地⽅。 下⼀节细说。

四、Binder:⼀次绑定发⽣了什么绑定的调度中⼼只有⼀个⽅法:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java:423

private <T> @Nullable Object bindObject(ConfigurationPropertyName name, Bindable<T> target, BindHandler handler,
Context context, boolean allowRecursiveBinding) {
ConfigurationProperty property = findProperty(name, target, context);
if (property == null && context.depth != 0 && containsNoDescendantOf(context.getSources(), name)) {
return null; // ←剪枝
}
AggregateBinder<?> aggregateBinder = getAggregateBinder(target, context);
if (aggregateBinder != null) { return bindAggregate(name, target, handler, context, aggregateBinder); }
if (property != null) {
try { return bindProperty(target, context, property); }
catch (ConverterNotFoundException ex) {

// We might still be able to bind it using the recursive binders

boolean fallbackToDefaultValue = ObjectUtils.isEmpty(property.getValue());
Object instance = bindDataObject(name, target, handler, context, allowRecursiveBinding, fallbackToDefaultValue);
if (instance != null) { return instance; }
throw ex;
}
}
return bindDataObject(name, target, handler, context, allowRecursiveBinding, false);
}

分派顺序清清楚楚:聚合(Map/Collection/数组) > 标量 > 数据对象。中间那个 catch (ConverterNotFoundException) 是个很朴素的补救:转不动就当它是个嵌套对象再试⼀次。

那句剪枝值得多看⼀眼。它问的是"所有源⾥还有没有以这个名字为前缀的后代",⽽答案有三态: PRESENT / ABSENT / UNKNOWN 。只有全体都明确说 ABSENT ,整棵⼦树才不必递归。⽽不可枚举的源只能回答 UNKNOWN ——于是绑定退化成"每个属性都得挨个试⼀遍"。这就是"源能不能枚举"值多少钱的地⽅。

顶层的 bind 外⾯还裹着⼀件事:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java:367

try (ConfigurationPropertyCaching.CacheOverride cacheOverride = this.configurationPropertyCaching.override()) {

✨ ⼀次绑定期间临时打开缓存, try-with-resources 结束即恢复。 ⼀次绑定内部要对同⼀批源反复发问,开缓存收益极⼤;但不能永久开,否则可变源的更新就看不⻅了。这是个

把"作⽤域"⽤语⾔机制表达出来的漂亮写法。

三个 DataObjectBinder,以及⼀条静默失败的路// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/Binder.java:220

dataObjectBinders.put(BindMethod.VALUE_OBJECT, List.of(valueObjectBinder));
dataObjectBinders.put(BindMethod.JAVA_BEAN, List.of(javaBeanBinder));
dataObjectBinders.put(null, List.of(valueObjectBinder, javaBeanBinder)); //未指定:先构造器,再 setter

构造器绑定这⼀路( ValueObjectBinder )有⼀条关键语义:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java:86

boolean bound = false;
for (ConstructorParameter parameter : parameters) {
Object arg = parameter.bind(propertyBinder);
bound = bound || arg != null;
arg = (arg != null) ? arg : getDefaultValue(context, parameter);
args.add(arg);
}

...

if (bound) { return valueObject.instantiate(args); }

只要有任意⼀个参数绑上了,就实例化整个对象;⼀个都没绑上,返回 null。

⚠ ⽽这⾥藏着 Boot ⽣态最阴的坑之⼀。构造器绑定要拿参数名,拿不到就废——可它默认不吭声:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/ValueObjectBinder.java:408

private static final ParameterNameDiscoverer LENIENT = new Discoverer(DEFAULT_DELEGATE, (message) -> {

}); // ←吞掉

private static final ParameterNameDiscoverer STRICT = new Discoverer(DEFAULT_DELEGATE, (message) -> {
throw new IllegalStateException(message.toString());
});

那条被吞掉的消息⻓这样( :436 ):

"Unable to use value object binding with constructor [%s] as parameter names cannot be discovered. "

+ "Ensure that the compiler uses the '-parameters' flag"

正常绑定⾛ LENIENT ( :79 、 :107 ),只有在创建实例已经失败之后才⽤ STRICT 再跑⼀遍、把这条提示作为 suppressed 异常补上( :122 )。

这就是"没加 -parameters 时构造器绑定神秘地全空"的答案。 Boot 的 Gradle/Maven 插件默认会加这个编译参数,所以⼤多数⼈⼀辈⼦碰不到;可⼀旦是⼿⼯构建、⾮标准 IDE配置、或者从别的构建体系迁过来,你会看到⼀个所有字段都是 null 的配置对象,没有任何⼀⾏⽇志告诉你为什么。

我认为这是个可以做得更好的地⽅:在"⽬标类型明显是给构造器绑定⽤的(⽐如是 record)、参数名却拿不到"这个组合下,完全有条件直接告警,⽽不是等到别处炸了再作为suppressed 异常挂上去。静默的失败⽐响亮的失败贵⼗倍。

List 覆盖,Map 合并——⼀对最容易记反的语义// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/CollectionBinder.java:58

protected Collection<Object> merge(Supplier<Collection<Object>> existing, Collection<Object> additional) {
Collection<Object> existingCollection = getExistingIfPossible(existing);
if (existingCollection == null) { return additional; }
try {
existingCollection.clear(); // ←先清空
existingCollection.addAll(additional);
return copyIfPossible(existingCollection);
} ...
}

⽽且集合绑定在源之间是短路的:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/IndexedElementsBinder.java:72

for (ConfigurationPropertySource source : getContext().getSources()) {
bindIndexed(source, name, target, elementBinder, result, aggregateType, elementType);
if (result.wasSupplied() && result.get() != null) { return; } // ←第⼀个有值的源赢,后⾯根本不看
}

Map 则完全相反,遍历所有源、逐个 putAll ,不短路:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/MapBinder.java:75

Map<Object, Object> map = createMap(target);
for (ConfigurationPropertySource source : getContext().getSources()) {
if (!ConfigurationPropertyName.EMPTY.equals(name)) { source = source.filter(name::isAncestorOf); }
new EntryBinder(name, resolvedTarget, elementBinder).bindEntries(source, map);
}
return map.isEmpty() ? null : map;
⽂档把这对⾏为写成了⽤户可⻅的规则:「When lists are configured in more than one place, overriding works by replacing the entire list.」( .../external-
config.adoc:1179 )、「for the same property in multiple sources, the one with the highest priority is used.」( :1233 )。

记法: List 整体替换, Map 逐 key 合并。最常⻅的误解是"我在 application-prod.yml ⾥加⼀⾏,应该是往 application.yml 的列表后⾯追加吧"——不会,整条列表被换掉。

五、两个反直觉的默认值注解本体只有 87 ⾏,其中两⾏值得单独拎出来:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationProperties.java:78

boolean ignoreInvalidFields() default false;

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationProperties.java:85

boolean ignoreUnknownFields() default true;

翻译成⼈话:

类型写错了 → 直接炸( ignoreInvalidFields=false );
key 拼错了 → 静默忽略( ignoreUnknownFields=true )。

跟⼤多数⼈的直觉正好相反。这两个开关最终体现在 handler 链的装配上:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java:113

private <T> BindHandler getBindHandler(Bindable<T> target, ConfigurationProperties annotation) {
List<Validator> validators = getValidators(target);
BindHandler handler = getHandler();
handler = new ConfigurationPropertiesBindHandler(handler);
if (annotation.ignoreInvalidFields()) { handler = new IgnoreErrorsBindHandler(handler); }
if (!annotation.ignoreUnknownFields()) { handler = new NoUnboundElementsBindHandler(handler, new UnboundElementsSourceFilter()); }
if (!validators.isEmpty()) { handler = new ValidationBindHandler(handler, validators.toArray(new Validator[0])); }
for (ConfigurationPropertiesBindHandlerAdvisor advisor : getBindHandlerAdvisors()) { handler = advisor.apply(handler); }
return handler;
}

⼀层层往外裹的装饰器,教科书级别的写法。但注意第 5 ⾏:只有当你把 ignoreUnknownFields 显式设成 false , NoUnboundElementsBindHandler 才会被装上。默认不装。

这是本章第⼆条批评,⽽且我认为它⽐第⼀条更值钱。 my.app.timout=5000 (少个 e )不会有任何提示——不报错、不警告、不打⽇志,你的超时就是默认值。Spring 团队的取舍逻辑不难猜:配置⽂件是共享的,⼀份 application.yml ⾥往往混着好⼏个模块的属性,对 A 模块⽽⾔的"未知字段"很可能是 B 模块的合法字段,默认严格会让绝⼤多数应⽤起不来。这个取舍在⼯程上是对的。

但代价必须说清楚:Spring Boot 的配置系统,默认对"你写错了"这件事保持沉默。 这跟⾃动配置那套"为什么这个 Bean 没⽣效"的⿊箱是同⼀种病——链路极⻓,失败极安静,靠猜是猜不出来的。真要防,只能靠 IDE 的元数据补全( spring-boot-configuration-processor )在写的时候拦⼀道,或者对你⾃⼰的模块显式打开 ignoreUnknownFields =false 。

handler 链⾥还有⼀个不起眼但很关键的⼩动作:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesBinder.java:240

return isConfigurationProperties(target.getType().resolve())
? target.withBindRestrictions(BindRestriction.NO_DIRECT_PROPERTY) : target;

如果⽬标类型⾃⼰标了 @ConfigurationProperties ,就禁⽌"把 my.props=xxx 这个标量直接转成整个对象"。 防的是⽤户⼿滑把整个前缀设成了⼀个字符串。

六、 @Value 还是 @ConfigurationProperties官⽅⽂档给了⼀张三⾏的对照表( .../external-config.adoc:1432 ⼀带):

Feature @ConfigurationProperties @ValueRelaxed binding Yes LimitedMeta-data support Yes NoSpEL evaluation No Yes

那个 "Limited" 值得掰开。它 limited 在哪,答案就在前⾯那⾏ ConfigurationPropertyName.of(key, true) :

你写的 key 是规范形(全⼩写 + 短横线,如 demo.item-price )→ 解析成功 → ⾛宽松匹配 → 能命中 demo.itemPrice 、 DEMO_ITEMPRICE ;

你写的 key 不规范(如 demo.itemPrice ,含⼤写)→ of(..., true) 返回 null → 退回 PropertySourcesPropertyResolver 的逐源精确匹配。此时能命中字⾯量demo.itemPrice ;⾄于还能命中 DEMO_ITEMPRICE ,那是 Framework ⾃⼰的兜底,跟 Boot 的宽松绑定没关系:

// [framework] spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java:33

* <li>{@code foo.bar} - the original name</li>
* <li>{@code foo_bar} - with underscores for periods (if any)</li>
* <li>{@code FOO.BAR} - original, with upper case</li>
* <li>{@code FOO_BAR} - with underscores and upper case</li>
这正好复现了⽂档⾥那句话:「 @Value("${demo.item-price}") 能拿到 demo.item-price 、 demo.itemPrice ,以及环境⾥的 DEMO_ITEMPRICE ;若写
@Value("${demo.itemPrice}") ,则 demo.item-price 不会被考虑。」( .../external-config.adoc:1454-1455 )

⼀句话结论: @Value 的宽松是「源侧」的宽松(Framework 的环境变量源 + Boot 挂的影⼦源), @ConfigurationProperties 的宽松是「名字侧」的宽松。两者交集之外,就会出现"明明配了却读不到"。所以——⽤ @Value 就⽼⽼实实写规范名:全⼩写 + 短横线。

另外三条真实差异:

  1. SpEL: @ConfigurationProperties 不解析 SpEL,注解 javadoc 原话是「Note that contrary to @Value , SpEL expressions are not evaluated since property values
are externalized.」( [boot] .../ConfigurationProperties.java 类 javadoc)。
  1. 占位符解不开时的⾏为不同。绑定这条路⽤的是 PropertySourcesPlaceholdersResolver ,它构造 PropertyPlaceholderHelper 时最后⼀个参数传了 true :

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/bind/PropertySourcesPlaceholdersResolver.java:53

this.helper = (helper != null) ? helper
: new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX,

SystemPropertyUtils.PLACEHOLDER_SUFFIX, SystemPropertyUtils.VALUE_SEPARATOR,

SystemPropertyUtils.ESCAPE_CHARACTER, true);
那个 true 在 Framework 侧的形参名叫 ignoreUnresolvablePlaceholders ( [framework] spring-
core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java:64-66 )。即: @ConfigurationProperties 这条路上解不开的 ${} 原样保留,不抛

异常。 ⽽ @Value 那条路默认解不开就炸。同⼀个 ${} ,两种脾⽓。

3. 元数据/IDE 补全只有 @ConfigurationProperties 有。 本基线还新增了⼀个专供元数据的注解 @ConfigurationPropertiesSource (源码 @since 4.0.0 , [boot]
core/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesSource.java ),javadoc 说得很明⽩:「This

annotation has no effect on the actual binding process, but serves as a hint to the spring-boot-configuration-processor」——只影响元数据⽣成,不影响绑定。

七、谁覆盖谁:⼀个⽅向陷阱,和⼀串真实机制现在到本章分量最重的⼀块。

陷阱先摆出来官⽅⽂档的优先级清单是这么开头的:

[boot] .../external-config.adoc:10Later property sources can override the values defined in earlier ones.后⾯的覆盖前⾯的。

⽽ Framework 的解析器是这么⼯作的:

// [framework] spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java:73

for (PropertySource<?> propertySource : this.propertySources) {
Object value = propertySource.getProperty(key);
if (value != null) { ... return ...; } //第⼀个命中的就返回
}
前⾯的赢。( addFirst 优先级最⾼、 addLast 最低, [framework] spring-
core/src/main/java/org/springframework/core/env/MutablePropertySources.java:103 、 :113 )

两个"顺序"⽅向正好相反。读⽂档时想的是"清单越往下越⼤",读代码时看到的是"列表越靠前越⼤"。这是这⼀⽚最容易串的地⽅,没有之⼀——记住:⽂档的清单是「语义优先级从低到⾼」,代码⾥的列表是「查找顺序从先到后」,后者反过来才等于前者。

⽂档那份清单( .../external-config.adoc:13 起,从低到⾼):默认属性 → @PropertySource → Config data( application.properties 之类) → random.* → OS 环境

变量 → Java 系统属性 → JNDI → ServletContext / ServletConfig 初始化参数 → SPRING_APPLICATION_JSON → 命令⾏参数 → 测试的 properties →@DynamicPropertySource → @TestPropertySource → Devtools 全局设置。

三条要背下来的:命令⾏打赢环境变量,环境变量打赢配置⽂件; -D 系统属性打赢 FOO= 环境变量(后者由 [framework] .../StandardEnvironment.java 的 javadoc 明写:

「Properties present in systemProperties will take precedence over those in systemEnvironment 」); setDefaultProperties 永远垫底。

垫底这件事是被强制执⾏的:

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

ConfigurationPropertySources.attach(environment);
listeners.environmentPrepared(bootstrapContext, environment); // ← ConfigData在这⾥跑
ApplicationInfoPropertySource.moveToEnd(environment);
DefaultPropertiesPropertySource.moveToEnd(environment); // ←强制踢到最后
⽽命令⾏是被强制插到最前的( :529 : sources.addFirst(new SimpleCommandLinePropertySource(args)) )。

鸡⽣蛋:profile 是从配置⾥读出来的配置⽂件这⼀整套的⼊⼝是⼀个 EnvironmentPostProcessor :

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentPostProcessor.java:52

public static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 10;

(类 javadoc 标 @since 2.4.0 ——这套 ConfigData 体系是 2.4 那次重写的产物。)

它把活⼉交给 ConfigDataEnvironment ,⽽那⾥有⼀个五步⽅法,是整套设计的全部精髓:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:236

void processAndApply() {
ConfigDataImporter importer = new ConfigDataImporter(this.logFactory, this.notFoundAction, this.resolvers, this.loaders);
registerBootstrapBinder(this.contributors, null, DENY_INACTIVE_BINDING);
ConfigDataEnvironmentContributors contributors = processInitial(this.contributors, importer);
ConfigDataActivationContext activationContext = createActivationContext(
contributors.getBinder(null, BinderOption.FAIL_ON_BIND_TO_INACTIVE_SOURCE));
contributors = processWithoutProfiles(contributors, importer, activationContext);
activationContext = withProfiles(contributors, activationContext);
contributors = processWithProfiles(contributors, importer, activationContext);
applyToEnvironment(contributors, activationContext, importer.getLoadedLocations(), importer.getOptionalLocations());
}

读法: spring.profiles.active 本身写在配置⽂件⾥,可"该读哪些配置⽂件"⼜取决于 profile。解法是分两轮:先读⼀轮不带 profile 的( processWithoutProfiles ),从⾥⾯把

profile 推导出来( withProfiles ),再带着 profile 读第⼆轮( processWithProfiles )。

对应的两个阶段被建模成枚举:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java:518

enum ImportPhase { BEFORE_PROFILE_ACTIVATION, AFTER_PROFILE_ACTIVATION; ... }

🦴 为什么 application-prod.yml ⼀定盖过 application.yml

这个答案⾥没有任何优先级数字,全靠两件事叠出来:遍历顺序 + addLast 。

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java:557

private ContributorIterator() {
this.phase = ImportPhase.AFTER_PROFILE_ACTIVATION; // ←先遍历 AFTER
this.children = getChildren(this.phase).iterator();
this.current = Collections.emptyIterator();
}

⾛完 AFTER 才切 BEFORE ( :590-593 ),最后才轮到⾃身( :595-598 )。⽽应⽤时是:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:358

for (ConfigDataEnvironmentContributor contributor : contributors) {

...

propertySources.addLast(propertySource);
}

先被 addLast 的,排在列表更前⾯;⽽列表越前优先级越⾼。 于是: AFTER_PROFILE_ACTIVATION (= profile 特定的⽂档)先被遍历 → 先 addLast → 排前⾯ → 赢。

⚠ 这是我要点破的第三条。这条⾄关重要的⽤户可⻅规则——"profile ⽂件覆盖通⽤⽂件"——在代码⾥没有任何⼀处显式表达。它是"迭代器构造函数⾥先取

AFTER"和"applyContributor ⽤ addLast"两个局部决策的乘积。改动其中任何⼀个,⾏为就翻转,⽽这两处相距两个⽂件、⼏百⾏。

🦴 同⽬录下 .properties 为什么打赢 .yaml :两次反转

同样的味道,更极端⼀点。⽂档只有⼀句 NOTE:「If you have configuration files with both .properties and YAML format in the same location, .properties takes

precedence.」( .../external-config.adoc:42 )代码⾥的链条是四环:

第 1 环 —— loader 的注册顺序,properties 在前:

[boot] core/spring-boot/src/main/resources/META-INF/spring.factories:8-10

org.springframework.boot.env.PropertySourceLoader=\

org.springframework.boot.env.PropertiesPropertySourceLoader,\org.springframework.boot.env.YamlPropertySourceLoader第 2 环 —— ⽣成候选引⽤时⽤ addFirst ,顺序反转:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java:202

Deque<StandardConfigDataReference> references = new ArrayDeque<>();
for (PropertySourceLoader propertySourceLoader : this.propertySourceLoaders) {
for (String extension : propertySourceLoader.getFileExtensions()) {
StandardConfigDataReference reference = new StandardConfigDataReference(...);
if (!references.contains(reference)) { references.addFirst(reference); }
}
}

此时顺序变成 yaml, yml, xml, properties 。

第 3 环 —— 加载时倒着循环,再反转⼀次:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataImporter.java:117

Map<ConfigDataResolutionResult, ConfigData> result = new LinkedHashMap<>();
for (int i = candidates.size() - 1; i >= 0; i--) {

转回 properties, xml, yml, yaml 。

第 4 环 —— 按这个顺序建贡献者、按序 addLast → properties 排在 yaml 前⾯ → 赢。

两次反转,负负得正。 结论是对的,可这条链⼦任何⼀环单看都不像在表达"properties 优先";它是⼀个涌现⾏为。我不认为这是好设计——⼀个明确写在⽂档⾥、⽤户会依赖的⾏为契约,应该有⼀处显式的代码来承载它,哪怕只是⼀个带注释的⽐较器。现在这样,它只被单元测试守着;任何⼈重构其中⼀环,都可能在不知情的情况下把它翻过来。

(顺带⼀提,同⼀个⽂件⾥的多⽂档也是倒序加进贡献者的,所以⽂件⾥靠后的⽂档优先级更⾼——对应⽂档 :596 那句「Documents are processed in order, from top to bottom.

Later documents can override...」。)

默认搜索位置// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:91

static final ConfigDataLocation[] DEFAULT_SEARCH_LOCATIONS;
static {
List<ConfigDataLocation> locations = new ArrayList<>();
locations.add(ConfigDataLocation.of("optional:classpath:/;optional:classpath:/config/"));
locations.add(ConfigDataLocation.of("optional:file:./;optional:file:./config/;optional:file:./config/*/"));
DEFAULT_SEARCH_LOCATIONS = locations.toArray(new ConfigDataLocation[0]);
}

两个"位置组",组内⽤ ; 分隔。外部⽂件( file: )优先级⾼于 jar 内( classpath: ),这靠的⼜是⼀次倒序:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:213

for (int i = locations.length - 1; i >= 0; i--) {
addInitialImportContributors(initialContributors, List.of(locations[i]));
}
回源核实过的⼏个默认值(别记⽹上的旧说法): - spring.config.name 缺省是 {"application"} ( [boot] .../StandardConfigDataLocationResolver.java:67 ); -
spring.config.on-not-found 缺省是 ConfigDataNotFoundAction.FAIL ( [boot] .../ConfigDataEnvironment.java:147-
148 , .orElse(ConfigDataNotFoundAction.FAIL) )——所以默认位置全都带 optional: 前缀,不然找不到就起不来; - 默认 profile 是 "default" ( [framework] spring-
core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:100 , RESERVED_DEFAULT_PROFILE_NAME ); - 属性名 spring.profiles.active /
spring.profiles.default (同⽂件 :77 、 :88 )。

spring.config.import :被引进来的⽂件,优先级更⾼// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java:55

ConfigDataProperties(@Name("import") @Nullable List<ConfigDataLocation> imports, @Nullable Activate activate) {

( @Name("import") 是因为 import 是 Java 关键字,构造器参数没法这么叫——⼀个很实在的⼩细节。)

语义在⽂档⾥( .../external-config.adoc:280 ):「Imports are processed as they are discovered, and are treated as additional documents inserted immediately below

the one that declares the import.」——被 import 进来的⽂件,优先级⾼于触发它的⽂件;⽽且 import 写在⽂档的哪⼀⾏不影响结果。去重也做了: ConfigDataImporter ⽤⼀

个 Set<ConfigDataResource> loaded 保证同⼀资源只加载⼀次,⽂档对应句是「Properties files are only ever loaded once.」( :271 )。
三种 resolver / loader 在 spring.factories:12-22 注册: configtree: (K8s ConfigMap/Secret 挂载卷)、 env: (把整份 properties 塞进⼀个多⾏环境变量)、以及兜底的
Standard ——后者 isResolvable 恒 true 、 getOrder() 是 LOWEST_PRECEDENCE 。

⼋、两个 Profile,不是⼀回事最后拆⼀组极易混淆的东⻄。

Framework 侧的 @Profile (源码 @since 3.1 )其实只是个 @Conditional :

// [framework] spring-context/src/main/java/org/springframework/context/annotation/ProfileCondition.java:37

public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, @Nullable Object> attrs = metadata.getAllAnnotationAttributes(Profile.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
if (context.getEnvironment().matchesProfiles((String[]) value)) { return true; }
}
return false;
}
return true;
}

它决定的是——这张图纸要不要进图纸库(bean 要不要注册),发⽣在 refresh() 期间。

Boot 侧的 spring.config.activate.on-profile 决定的是——这份配置⽂档要不要⽣效,发⽣在 environment 准备期,⽐前者早得多:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java:122

boolean isActive(@Nullable ConfigDataActivationContext activationContext) {
if (activationContext == null) { return false; }
CloudPlatform cloudPlatform = activationContext.getCloudPlatform();
boolean activate = isActive((cloudPlatform != null) ? cloudPlatform : CloudPlatform.NONE);
activate = activate && isActive(activationContext.getProfiles());
return activate;
}
🦴 注意 matchesActiveProfiles ⾥那句 org.springframework.core.env.Profiles.of(this.onProfile).matches(...) —— on-profile ⾛的是 Framework 的

profile 表达式,⽀持 prod | staging 、 !dev 、 & 这类组合,不是简单的字符串相等。

⚠ 还有⼀条⾃举保护。这些属性不许写在 profile 特定的⽂件⾥:

// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/InvalidConfigDataPropertyException.javaPROFILE_SPECIFIC_ERRORS: spring.profiles.include / spring.profiles.active / spring.profiles.default(含 [0] 形式)