第17章 卷五 · 总装房 · 环境与配置源:Environment
环境与配置源:Environment"我不⽣产配置。我只是把⼀摞账本按顺序摆好,然后从上往下翻——第⼀本翻到的,就作数。" —— PropertySourcesPropertyResolver ,如果它肯说话⼀桩没有⽬击者的悬案先讲⼀个我⻅过⾄少四遍的现场。
某个服务在预发环境跑得好好的,⼀上⽣产就连不上数据库。 application-prod.yml ⾥ spring.datasource.url 写得清清楚楚,格式没问题,YAML 缩进没问题,profile 也确实激活了 prod ——启动⽇志第⼀⾏就打着 The following 1 profile is active: "prod" 。可 HikariPool 抛出来的连接串,是空的。
排查的⼈把 YAML 反复看了六遍,把 profile 判定逻辑翻了个底朝天,最后是运维在部署脚本⾥找到的:
export SPRING_DATASOURCE_URL=""那是三个⽉前⼀个⼈为了"临时清⼀下"留下的。它是⼀个空串。
于是这⼀章可以从这⾥开始了。因为要解释这件事,你需要同时知道三件事:环境变量为什么能变成 spring.datasource.url (它明明⻓得完全不⼀样)、环境变量为什么压得过application-prod.yml (直觉上"我⾃⼰写的⽂件"应该更权威)、以及最狠的那条——空串为什么算数。
三个答案全在同⼀个包⾥,⽽且加起来不到四千⾏代码。
[framework] spring-core/src/main/java/org/springframework/core/env/ ⼀共 25 个⽂件、3934 ⾏。这就是 Spring 全部配置能⼒的地基。上⾯盖着 Boot 那套⼏万⾏的 config data、松散绑定、 @ConfigurationProperties ,但地基只有这么⼤——⽽且它做的事只有⼀件。
这⼀章要讲的,是坊⾥的账房。
图纸库管"怎么造",作坊管"照图造出来",总装房管"把差事⼀并办了"。账房不管造器,它只管⼀件事:当有⼈问"这个值是多少",从哪⼀摞账本⾥、按什么次序去翻。
⼀、⼆⼗⾏的⼼脏先把最重要的⼀段代码放上来。整本书⾥,论"代码量与影响⾯之⽐",没有⼏段能超过它。
// [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) {
if (logger.isTraceEnabled()) {
logger.trace("Searching for key '" + key + "' in PropertySource '" +
propertySource.getName() + "'");
}
Object value = propertySource.getProperty(key);
if (value != null) {
if (resolveNestedPlaceholders) {
if (value instanceof String string) {
value = resolveNestedPlaceholders(string);
}
else if ((value instanceof CharSequence cs) && (String.class.equals(targetValueType) ||
CharSequence.class.equals(targetValueType))) {
value = resolveNestedPlaceholders(cs.toString());
}
}
logKeyFound(key, propertySource, value);
return convertValueIfNecessary(value, targetValueType);
}
}

}...
return null;
}做了什么顺序遍历⼀个 PropertySource 列表,谁先给出⾮ null 的值,谁就赢,⽴刻返回,后⾯的源⼀律不再问。
为什么这么设计因为"谁覆盖谁"根本不是⼀条规则,它是⼀个位次。
Spring 没有任何⼀处代码在做"合并"、"加权"、"深度 merge"、"按来源类型判定优先级"。它只有⼀个 List ,和⼀个 for 。你以为的那套复杂的覆盖策略,在实现层⾯就是——列表下标越⼩,越先被问到。
这个选择带来的好处是巨⼤的:任何⼈都可以往列表⾥插⼀个源,插在任何位置,⽽不需要修改任何"优先级枚举"或"权重表"。Boot 后来往这个列表⾥塞了⼗⼏个源,Framework 这边⼀⾏代码都没改。
代价是:优先级变成了⼀个运⾏期的、不可静态检查的、只有摆在⼀起看才知道结果的东⻄。 这就是所有"我明明配了怎么不⽣效"的物理起点。
精妙或坑在哪
看 if (value != null) 这⼀⾏。判据是 value != null 。不是"这个 key 存不存在",更不是"这个值有没有内容"。
所以开场那个案⼦的答案是: SPRING_DATASOURCE_URL="" 给出的值是空串 "" ,不是 null 。它赢了。 application-prod.yml ⾥那个正确的连接串,从头到尾没有被问到过⼀次。
更冷酷的是下⾯这段:
// [framework] spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java:114
protected void logKeyFound(String key, PropertySource<?> propertySource, Object value) {
if (logger.isDebugEnabled()) {
logger.debug("Found key '" + key + "' in PropertySource '" + propertySource.getName() +
"' with value of type " + value.getClass().getSimpleName());
}
}
它打了 key,打了源名,打了值的类型——就是不打值。上⾯的 javadoc( :105-107 )解释了原因:"As of 4.3.3, this does not log the value anymore in order to avoid accidentallogging of sensitive settings."
这是⼀个我完全理解、但必须点破代价的取舍。为了不把密码写进⽇志,Spring 放弃了告诉你"我拿到的是个空串"的能⼒。 你打开 DEBUG,能看到 Found key'spring.datasource.url' in PropertySource 'systemEnvironment' with value of type String ——你会知道它来⾃环境变量,但你不会知道它是空的。⽽这两条信息⾥,后者才是你要的那条。
排这类问题,唯⼀可靠的办法是⾃⼰写⼀⾏:
System.out.println("[" + env.getProperty("spring.datasource.url") + "]");那对⽅括号不是装饰,是唯⼀能让你看⻅空串的东⻄。
⼆、⼀摞账本: MutablePropertySources既然⼀切都是位次,那这个列表本身就值得单独看⼀眼。
// [framework] spring-core/src/main/java/org/springframework/core/env/MutablePropertySources.java:43
private final List<PropertySource<?>> propertySourceList = new CopyOnWriteArrayList<>();
⼀个 CopyOnWriteArrayList 。类级 javadoc( :32-34 )把语义钉死了:"Whereprecedence is mentioned in methods such as addFirst and addLast , this is with regard to the order in which property sources will be searched."
⼀句话记法:list 的下标就是优先级,index 0 最⼤。
位次 API,全章最该背下来的⼀张表⽅法 ⾏ 语义
addFirst(ps) :103 插到 index 0 —— 最⾼优先级addLast(ps) :113 追加到尾部 —— 最低优先级addBefore(name, ps) :124 优先级"紧⾼于"某个具名源addAfter(name, ps) :137 优先级"紧低于"某个具名源
precedenceOf(ps) :149 返回下标,不在就 -1
remove(name) :157 按名字删⽅法 ⾏ 语义
replace(name, ps) :171 原地换⼈,位次不动上表全部来⾃ [framework] spring-core/src/main/java/org/springframework/core/env/MutablePropertySources.java 。
⼀个 equals 换来⼀整套运维语义这⼏个 API 全都按名字操作。 addBefore("systemEnvironment", mySource) ⾥那个字符串,是怎么找到对应对象的?
// [framework] spring-core/src/main/java/org/springframework/core/env/PropertySource.java:141@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof PropertySource<?> that &&
ObjectUtils.nullSafeEquals(getName(), that.getName())));
}
PropertySource 的 equals 只⽐名字。javadoc( :41-45 )写得毫不含糊:" PropertySource identity is determined not based on the content of encapsulated properties, but rather based on the name of the PropertySource alone."
这⼀个决定,⼀次买到了四样东⻄:
1. 按名字操作位次—— addBefore("systemEnvironment", ...) 成⽴。- replace 保位次——换掉内容,不动次序(第⼗⼀节 Boot 的 origin 追踪全靠这条)。
3. 重复 add 变成"移动"—— addFirst / addLast / addBefore / addAfter 四个⽅法进⻔第⼀件事都是 removeIfPresent(propertySource)( :105 / :115 / :127 / :140 ,实现在 :205 )。同名源再 add ⼀次,不会产⽣两份,⽽是被挪到新位置。这条幂等性后⾯会被 Boot 反复利⽤。
- 可以先占位、后换真身——下⾯这个。
// [framework] spring-core/src/main/java/org/springframework/core/env/PropertySource.java:210
public static class StubPropertySource extends PropertySource<Object> {
public StubPropertySource(String name) {
super(name);
}/**
* Always returns {@code null}.*/
@Override
public @Nullable String getProperty(String name) {
return null;
}
}⼀个永远返回 null 的假账本。javadoc( :196-207 )说明了⽤途:某些源(典型如 ServletContext )在 context 创建那⼀刻还拿不到,于是先放⼀个同名的空册⼦把位置占住,等refresh 时再 replace 成真货。
这是"位次先于内容"这个设计思想最⾚裸的⼀次表达:Spring 宁可在账房桌上摆⼀本⼀⻚字都没有的空账本,也不允许优先级顺序在运⾏期漂移。
⽤它的地⽅在 [framework] spring-web/src/main/java/org/springframework/web/context/support/StandardServletEnvironment.java:110-111 ,连放两个桩: servletConfigInitParams 和 servletContextInitParams 。
还有⼀个更极端的: ComparisonPropertySource ( PropertySource.java:232 ), PropertySource.named(name) ( :193 )返回的就是它,除了 equals / hashCode / toString之外任何⽅法都抛 UnsupportedOperationException 。它存在的唯⼀意义,是喂给 List.indexOf() 做查找。⼀个只为了被⽐较⽽⽣的对象。
🦴 锁的形状
容器是 CopyOnWriteArrayList (读⽆锁、迭代拿快照),但所有写操作⼜都套了⼀层 synchronized (this.propertySourceList) ( :104 、 :114 、 :126 …)。为什么两套都要?
COW 保证读者永远不会 ConcurrentModificationException ——⼀次 getProperty 的遍历中途,别⼈往列表⾥插源,你不会崩。
synchronized 是为了让"先 removeIfPresent 再 add "这种复合操作保持原⼦:否则两个线程同时 addFirst 同⼀个名字,可能真的插进去两份。
代价写在暗礁⾥:⼀次查找看到的是开始迭代那⼀刻的快照。启动期各种 EnvironmentPostProcessor 正在往⾥塞源的时候,如果有别的线程在读,它读到的是⼀个"半新半旧的世界观"。不会报错,只是不对。
三、柜台与账房先⽣: Environment 其实不翻账本现在看⻔⾯。这⼀层有个很多⼈没注意到的事实: Environment ⾃⼰不⼲活。
三层接⼝摞在⼀起:
PropertyResolver [framework] .../env/PropertyResolver.java:31
└── Environment [framework] .../env/Environment.java:71 (+ profile 判定)
└── ConfigurableEnvironment [framework] .../env/ConfigurableEnvironment.java:71extends Environment, ConfigurablePropertyResolver
Environment 继承 PropertyResolver ——所以 environment.getProperty("x") 能⽤。但 Environment ⾃⼰只加了四个⽅法,全是 profile 相
关: getActiveProfiles() ( :87 )、 getDefaultProfiles() ( :96 )、 matchesProfiles(String...) ( :113 , @since 5.3.28 )、 acceptsProfiles(Profiles)
( :149 , @since 5.1 )。还有⼀个 acceptsProfiles(String...) 在 :136 ,头上顶着 @Deprecated(since = "5.1") 。别再写这个重载了,它没有表达式能⼒。
再往下看⻣架:
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:109
private final MutablePropertySources propertySources;
private final ConfigurablePropertyResolver propertyResolver;
protected AbstractEnvironment(MutablePropertySources propertySources) {
this.propertySources = propertySources;
this.propertyResolver = createPropertyResolver(propertySources); // :137
customizePropertySources(propertySources); // :138
}
protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) { // :148
return new PropertySourcesPropertyResolver(propertySources);
}然后从 :495 ⼀路到 :588 ,近百⾏全是⼀模⼀样的⼀⾏转发:
@Override
public ConfigurableConversionService getConversionService() {
return this.propertyResolver.getConversionService();
}// ...中间省略⼆⼗来个同款@Override
public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
return this.propertyResolver.resolveRequiredPlaceholders(text);
}Environment 是柜台, PropertyResolver 是柜台后⾯真正翻账本的先⽣。 你隔着柜台说话,柜台原话传进去,先⽣翻完,原话传出来。近百⾏"抄写员"代码,⼀个逻辑都没有。
这看着很蠢。但 :148 那个 createPropertyResolver 是受保护的⼯⼚钩⼦,标着 @since 5.3.4 ——它的存在,让"柜台"和"翻账的先⽣"可以分别被替换。这个钩⼦在Framework 内部⼀次都没被覆写过;它的唯⼀重量级使⽤者,是 Spring Boot(第⼗⼀节会看到)。
换句话说:Framework 在 5.3.4 加了⼀个⾃⼰不⽤的钩⼦,专⻔给 Boot 留⻔。 没有这个钩⼦,Boot 4 没法把整条取值链换成⾃⼰的实现。
customizePropertySources 的两条纪律AbstractEnvironment 上 :161-239 那段是全包最⻓的⼀段注释,专⻔讲这个回调怎么写。两条:
第⼀条:⼦类应当⽤ addLast 。 这样"更深层的⼦类调 super.customizePropertySources() 时结果可预测"。javadoc 举了⼀个 Level1/Level2 两层继承的例⼦,还写了结
论:"The search order is now C, D, A, B as desired."( :208 )第⼆条, :226-235 标题就叫 "A warning about instance variable access":这个回调是在构造函数⾥被调⽤的,⼦类的实例字段此刻还没赋初值。 原⽂:"any initial value will not
yet be assigned when this callback is invoked by the AbstractEnvironment() constructor"。
只能赋值,不能读。 你在⾃定义 Environment 的字段上写个 private String prefix = "app."; ,然后在 customizePropertySources ⾥读 this.prefix ——拿到的是null 。这是⼀条写⾃定义 Environment 必踩⼀次的坑,⽽且 NPE 的堆栈会指向构造函数,⾮常难联想。
StandardEnvironment :默认只有两个源,⽽顺序有理由// [framework] spring-core/src/main/java/org/springframework/core/env/StandardEnvironment.java:95@Override
protected void customizePropertySources(MutablePropertySources propertySources) {
propertySources.addLast(
new PropertiesPropertySource(SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, getSystemProperties()));
propertySources.addLast(
new SystemEnvironmentPropertySource(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getSystemEnvironment()));
}
两个名字常量必须记住,因为它们会在 Boot ⽇志、actuator /env 端点⾥天天出现: "systemProperties" ( :61 )、 "systemEnvironment" ( :58 )。
顺序是 systemProperties > systemEnvironment。 理由不是拍脑袋,类 javadoc :34-37 写了:"system properties are per-JVM, while environment variables may be the same across many JVMs on a given system. Giving system properties precedence allowsfor overriding of environment variables on a per-JVM basis."
这是⼀条元规则的第⼀次出现,它会贯穿整章、贯穿 Boot 的全部⼗五级优先级:越贴近"这⼀次运⾏"的东⻄,优先级越⾼。 命令⾏参数⽐系统属性还贴近这⼀次运⾏,所以它更⾼;打进jar ⾥的 application.properties 是"所有运⾏共⽤的",所以它最低。整张优先级表都可以⽤这⼀句话推出来。
🦴 两个⼏乎没⼈知道的细节
其⼀: getSystemProperties() 返回的是活引⽤。
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:440
public Map<String, Object> getSystemProperties() {
return (Map) System.getProperties();
}没有拷⻉。运⾏期 System.setProperty("foo", "bar") 之后, environment.getProperty("foo") ⽴刻就能看⻅。这既是⼀个⽅便的后⻔,也是⼀个并发隐患。(环境变量那⼀侧是安全的—— System.getenv() 返回不可变 map,改不动。)
其⼆: spring.getenv.ignore 。
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:66
public static final String IGNORE_GETENV_PROPERTY_NAME = "spring.getenv.ignore";
:464 的 suppressGetenvAccess() 读它,默认 false 。置成 true 之后, getSystemEnvironment() 直接返回 Collections.emptyMap() ( :448 )——整条环境变量源变成空的。写单元测试想要⼀个⼲净环境时⾮常好⽤,⽽线上被⼈误设时会⾮常难查。
四、环境变量的宽松名字:⼀个能⼒,只属于⼀个源回到开场那个案⼦的第⼆问:环境变量 SPRING_DATASOURCE_URL ,是怎么被当成 spring.datasource.url 的?
答案在⼀个类⾥,⽽且只在这⼀个类⾥。
// [framework] spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java:107
protected final String resolvePropertyName(String name) {
Assert.notNull(name, "Property name must not be null");
String resolvedName = checkPropertyName(name);
if (resolvedName != null) {
return resolvedName;
}
String uppercasedName = name.toUpperCase(Locale.ROOT);
if (!name.equals(uppercasedName)) {
resolvedName = checkPropertyName(uppercasedName);
if (resolvedName != null) {
return resolvedName;
}
}
return name;
}checkPropertyName ( :123 )每次试四种写法:原样、 . → _ 、 - → _ 、 . 和 - 都→ _ 。外层跑两轮:原名⼀轮,全⼤写⼀轮。总共 8 种变体。
类 javadoc( :33-41 )举的例⼦: getProperty("foo.bar") 会依次试 foo.bar 、 foo_bar 、 FOO.BAR 、 FOO_BAR 。三条要点:
- ⽅向是单向的。 是拿"程序⾥的名字"去凑"环境变量的名字",不是反过来。环境变量 FOO_BAR 不会⾃动变成 foo.bar 出现在 getPropertyNames() ⾥——那个⽅法继承⾃ MapPropertySource ,返回的是原始 key。
2. containsProperty 被覆写成 getProperty(name) != null ( :84 ),这样宽松匹配对 contains 同样⽣效。
3. Locale.ROOT ( :113 )不是随⼿写的。 不加它,在⼟⽿其语 locale 下 "i".toUpperCase() 会得到 "İ" (带点的⼤写 I),于是 spring.profiles.active 变成SPRİNG.PROFİLES.ACTİVE ,匹配不上任何东⻄。这是 Java ⾥最古⽼的⼀个跨语⾔陷阱,Spring 在这⾥挡住了。
SPRING_PROFILES_ACTIVE 之所以能激活 profile,全部原因就是这个⽅法: spring.profiles.active → ⼤写 SPRING.PROFILES.ACTIVE → 点换下划线SPRING_PROFILES_ACTIVE → 命中。
AbstractEnvironment 的 :71-74 和 :81-85 两处 javadoc 都提到了这个⽤法(Bash 之类的 shell 不允许变量名带点)。但请记住⼀句话:
在纯 Framework ⾥,这个宽松查找的能⼒只属于 systemEnvironment 这⼀个源。 别的源没有。你⾃⼰ addLast ⼀个 MapPropertySource ,⾥⾯写
FOO_BAR , getProperty("foo.bar") 是拿不到的。(Boot 那边完全不是这样。它有⼀套作⽤范围⼤得多的松散绑定,第⼗⼀节讲。这两件事经常被混为⼀谈,⽽它们的适⽤范围差着量级。)
五、谁覆盖谁:先把⽅向问清楚现在到运维最困惑的地⽅了。开讲之前,必须先处理⼀个表述陷阱,否则后⾯全是⽩讲。
Spring 世界⾥存在两套⽅向相反的叙述。
源码与 Framework ⽂档的⼝径: MutablePropertySources 是⼀个优先级从⾼到低的列表,index 0 最⾼, addFirst 就是最⾼。
Boot 参考⽂档的⼝径:
"Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Later property sources can override the valuesdefined in earlier ones." —— [boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc:9-10然后 :13 起给的那张清单,是从低到⾼排的。
这两句话不⽭盾,但⽅向相反。排查问题时先问⾃⼰⼀句:我现在看的,是列表位次(越前越⼤),还是⽂档清单(越后越⼤)?
我认为这是 Spring ⽂档体系⾥⼀处真实的、可以改进的表达断层。同⼀个概念,在两个官⽅渠道⾥⽤了相反的排列⽅向,⽽且没有任何⼀处明确提醒读者"注意我们这⾥的顺序是反的"。绝⼤多数"我明明配了怎么不⽣效"的困惑,不是不知道规则,⽽是把⽅向搞反了。
表 A:Boot 官⽅的⼗五级(逐条抄⾃在仓⽂档,后⾯覆盖前⾯)
[boot] documentation/spring-boot-docs/src/docs/antora/modules/reference/pages/features/external-config.adoc:15-31 :
来源 备注
1 SpringApplication.setDefaultProperties(Map) 永远垫底2 @Configuration 类上的 @PropertySource ⽂档明确警告:refresh 才进 Environment,对 logging.* 和 spring.main.* 已经太晚
3 Config data( application.properties / YAML ⼀族) 展开⻅表 B
4 RandomValuePropertySource (只管 random.* )5 OS 环境变量
6 Java System properties( -D ) ⽐环境变量⾼,与 StandardEnvironment ⼀致
7 JNDI attributes( java:comp/env )8 ServletContext init 参数9 ServletConfig init 参数
10 SPRING_APPLICATION_JSON (内联 JSON)11 命令⾏参数 常规运⾏时的最⾼位12 测试上的 properties 属性13 @DynamicPropertySource14 @TestPropertySource
15 devtools 全局配置( $HOME/.config/spring-boot ) 最⾼开场那个案⼦的第⼆问,答案就在第 3 ⾏和第 5 ⾏之间:环境变量(5)⾼于 config data(3)。 这不是 bug,这是设计——容器化部署的整个模型都建⽴在"环境变量能覆盖打进镜像的配置⽂件"之上。
表 B:config data ⽂件之间(同⼀⽂档 :36-38 ,后⾯覆盖前⾯)
- jar 内的 application.properties / YAML
2. jar 内的 application-{profile}.properties / YAML- jar 外的 application.properties / YAML
4. jar 外的 application-{profile}.properties / YAML
同⻚两条 NOTE( :40-42 ):"It is recommended to stick with one format for your entire application."
"If you have configuration files with both .properties and YAML format in the same location, .properties takes precedence."
第⼆条请特别记住,第六节最后会把它的实现挖到底——那是本章最离奇的⼀段代码。
六、这套顺序在代码⾥是怎么⻓出来的上⾯两张表是结果。真正有价值的是:没有任何⼀个地⽅写着这张表。 它是五段互不相识的代码叠加出来的副产物。
(a) 启动时先摆好"已经在场的源"
// [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); // → addLast,垫底
}
if (this.addCommandLineProperties && args.length > 0) {...
sources.addFirst(new SimpleCommandLinePropertySource(args)); // :529 ←命令⾏ addFirst,最⾼
}
environment.getPropertySources().addLast(new ApplicationInfoPropertySource(this.mainApplicationClass)); // :532
}表 A 的第 1 ⾏(垫底)和第 11 ⾏(最⾼),就是这⾥的两⾏代码。省略号那⾥还有⼀个分⽀:命令⾏源如果已经存在,新的会被塞进⼀个 CompositePropertySource 的前⾯再replace 回去( :520-527 )——⼜⼀次利⽤了"replace 保位次"。
:532 那个 ApplicationInfoPropertySource (源名 "applicationInfo" )提供 spring.application.version 和 spring.application.pid 两个 key, addLast ,你随时可以覆盖掉。
(b) config data 加载完,⽤ addLast ⼀条条追加// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:359
for (ConfigDataEnvironmentContributor contributor : contributors) {
PropertySource<?> propertySource = contributor.getPropertySource();
if (contributor.getKind() == ConfigDataEnvironmentContributor.Kind.BOUND_IMPORT && propertySource != null) {
if (!contributor.isActive(activationContext)) {... //跳过没被激活的
}
else {
propertySources.addLast(propertySource); // :368...
}}
}全是 addLast 。所以先被迭代到的,位次更靠前,优先级更⾼。
那关键就变成了:这个 for 的迭代顺序是什么?
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java:557
private ContributorIterator() {
this.phase = ImportPhase.AFTER_PROFILE_ACTIVATION; //先吐"profile激活之后"的孩⼦...
}
private @Nullable ConfigDataEnvironmentContributor fetchIfNecessary() {...
if (this.phase == ImportPhase.AFTER_PROFILE_ACTIVATION) {
this.phase = ImportPhase.BEFORE_PROFILE_ACTIVATION; // :590再吐"profile激活之前"的孩⼦
this.children = getChildren(this.phase).iterator();
return fetchIfNecessary();
}
if (this.phase == ImportPhase.BEFORE_PROFILE_ACTIVATION) {
this.phase = null;
this.next = ConfigDataEnvironmentContributor.this; // :595最后吐⾃⼰
return this.next;
}
return null;
}AFTER → BEFORE → ⾃⼰。
AFTER_PROFILE_ACTIVATION 阶段的孩⼦,就是那些 profile-specific ⽂件( application-prod.yml )。它们先被迭代 → 先 addLast → 位次更靠前 → 优先级更⾼。
这就是" application-prod.yml 覆盖 application.yml "在源码层的全部物理原因。
这⾥有⼀处我很喜欢的设计:优先级被编码进了遍历顺序本身。没有⽐较器,没有 @Order ,没有优先级字段。想让 A 压过 B,就让迭代器先吐 A。
(c) jar 外压 jar 内:靠⼀个倒着的 for默认搜索位置只有两条:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:93
locations.add(ConfigDataLocation.of("optional:classpath:/;optional:classpath:/config/"));
locations.add(ConfigDataLocation.of("optional:file:./;optional:file:./config/;optional:file:./config/*/"));classpath: 在前(jar 内), file: 在后(jar 外)。但注册的时候:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:213
if (registerIndividually) {
for (int i = locations.length - 1; i >= 0; i--) {
addInitialImportContributors(initialContributors, List.of(locations[i]));
}
}倒着来。 于是 file: 那条先进 contributors 列表 → 先被迭代 → 优先级⾼于 classpath: 。表 B 的第 3、4 条成⽴。
(d) 两个源的精确落位
"defaultProperties" 的类 javadoc( [boot] core/spring-boot/src/main/java/org/springframework/boot/env/DefaultPropertiesPropertySource.java:34-35 )写着:"By convention, the DefaultPropertiesPropertySource is always the last property source in the Environment ." 为了兑现这句 "always",Boot 在三个地⽅各调了
⼀次 moveToEnd ( ConfigDataEnvironment 建 contributor 列表时、 applyToEnvironment ⾥ :345 、 SpringApplication.prepareEnvironment ⾥ :358 ),⽽
moveToEnd 的实现是"先 remove(NAME) 再 addLast "( DefaultPropertiesPropertySource.java:127 )——⼜是"按名字操作位次"。⽽ random 那个源⽤的是 addAfter :
// [boot] core/spring-boot/src/main/java/org/springframework/boot/env/RandomValuePropertySource.java:170
if (sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) != null) {
sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, randomSource);
}
else {
sources.addLast(randomSource);
}"紧贴在环境变量下⾯"——表 A 第 4、5 ⾏相邻,就是这⼀⾏的结果。这个源只认 random. 前缀,别的 key 直接返回 null。
(f) .properties 压 .yml :⼀条翻了四次⽅向的链这是本章最离奇的⼀段。前⾯那条 NOTE 说得像⼀条设计决策,但你在源码⾥找不到任何⼀处写着"properties 优先于 yaml"。它是四次⽅向翻转的净结果:
第⼀步, spring.factories ⾥ PropertySourceLoader 的注册顺序是 PropertiesPropertySourceLoader 在前、 YamlPropertySourceLoader 在后(扩展名分别是
properties / xml 与 yml / yaml )。第⼆步(翻转⼀):
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/StandardConfigDataLocationResolver.java:200
private Deque<StandardConfigDataReference> getReferencesForConfigName(...) {
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); // ←逐个前插
}
}
}
return references;
}addFirst 逐个前插,队列变成 yaml, yml, xml, properties。
第三步(翻转⼆):
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataImporter.java:118
for (int i = candidates.size() - 1; i >= 0; i--) {倒着 load,结果 LinkedHashMap 的顺序变回 properties, xml, yml, yaml。
第四、五步, ConfigDataEnvironmentContributors.asContributors 保持 map 顺序建 contributor 列表, ContributorIterator 按列表顺序迭代, applyContributor ⼀路addLast 。
净结果: properties > xml > yml > yaml 。我核这条链核了很久,最后的感受是:它是对的,但它的正确性是"算"出来的,不是"写"出来的。 中间任何⼀个⼈为了别的⽬的改掉⼀次遍历⽅向,这条⽂档承诺就会静默反转,⽽且不会有任何测试之外的东⻄告诉你。这是我在整个 config data 模块⾥看到的最脆的⼀处。Boot ⽂档那句 "It is recommended to stick with one format" 与其说是⻛格建议,不如说是⼀句⾃保。
🦴 顺带核出⼀条 YAML 专属事实: [boot] core/spring-
boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributors.java:183 对同⼀个⽂件内的多份 YAML ⽂档( --- 分隔)也做了⼀次倒序遍历——所以同⼀个 YAML ⽂件⾥,靠后的 --- 段优先级更⾼。这和"同⼀个 .properties ⽂件⾥后写的 key 覆盖先写的"直觉⼀致,但它是靠⼀⾏显式反转实现的,不是天然的。
七、profile:⼀个开关,两套算法现在换个话题。profile 不是配置源,它只是⼀个"哪些源该不该进队列、哪些 bean 该不该注册"的开关。
7.1 Framework 侧:懒读⼀次,读完冻结四个常量,都在 [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java :
常量 ⾏ 值ACTIVE_PROFILES_PROPERTY_NAME :77 "spring.profiles.active"
DEFAULT_PROFILES_PROPERTY_NAME :88 "spring.profiles.default"
RESERVED_DEFAULT_PROFILE_NAME :100 "default"
IGNORE_GETENV_PROPERTY_NAME :66 "spring.getenv.ignore"
激活逻辑:
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:272
protected Set<String> doGetActiveProfiles() {
synchronized (this.activeProfiles) {
if (this.activeProfiles.isEmpty()) { // ←只在空的时候读⼀次
String profiles = doGetActiveProfilesProperty();
if (StringUtils.hasText(profiles)) {
setActiveProfiles(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(profiles)));
}
}
return this.activeProfiles;
}
}三条:
读⼀次就定死。之后再改 spring.profiles.active 这个属性,不会有任何效果(除⾮有⼈显式再调 setActiveProfiles )。
trimAllWhitespace 是全串去空⽩,不是 trim 两端。所以 "a, b" 和 "a,b" 等价,但 profile 名字⾥不能含空格——你写 "my profile" ,拿到的是 myprofile 。
setActiveProfiles 是覆盖式的(先 clear() ),追加要⽤ addActiveProfile 。
默认 profile 的逻辑更绕⼀层。字段初值是 new LinkedHashSet<>(getReservedDefaultProfiles()) ( :107 ),⽽ getReservedDefaultProfiles() 返回
Collections.singleton("default") 。于是 doGetDefaultProfiles() ( :337 )判"要不要去读属性"的条件不是"是不是空",⽽是 if
(this.defaultProfiles.equals(getReservedDefaultProfiles())) ——"是不是还等于那个保留集"。默认 profile 集合的初值是 {"default"} ,不是空集。 这就是"什么都不配时 @Profile("default") 的 bean 会⽣效"的来源。
判定只有三⾏:
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:407
protected boolean isProfileActive(String profile) {
validateProfile(profile);
Set<String> currentActiveProfiles = doGetActiveProfiles();
return (currentActiveProfiles.contains(profile) ||
(currentActiveProfiles.isEmpty() && doGetDefaultProfiles().contains(profile)));
}default profiles 只在 active 集合「完全为空」时才起作⽤。
这条是 @Profile("default") 最常⻅的翻⻋点。你激活了⼀个跟它⼋竿⼦打不着的 metrics , default ⽴刻整体熄⽕。"default" 这个名字给⼈的暗示是"没有更好的选择时的兜底",但它的实际语义是"⼀个 profile 都没激活时的兜底"——差别很⼤。
还有 validateProfile ( :424 ):空/纯空⽩ → IllegalArgumentException("must contain text") ;以 ! 开头 → IllegalArgumentException("must not begin with! operator") 。profile 名字本身不许带 ! , ! 只能出现在表达式⾥。
7.2 表达式:⼀棵被编译成 lambda 的树[framework] spring-core/src/main/java/org/springframework/core/env/Profiles.java:34 是个 @FunctionalInterface ,核⼼只有⼀个⽅法:
boolean matches(Predicate<String> isProfileActive);
static Profiles of(String... profileExpressions) {
return ProfilesParser.parse(profileExpressions);
}
语法在 javadoc :53-63 : ! (NOT)、 & (AND)、 | (OR),以及⼀条硬规定—— & 和 | 不加括号不能混⽤。 "a & b | c" 是⾮法的,必须写成 "(a & b) | c" 或 "a & (b |
c)" 。这条规矩的实现只有两⾏:
// [framework] spring-core/src/main/java/org/springframework/core/env/ProfilesParser.java:81
case "&" -> {
assertWellFormed(expression, operator == null || operator == Operator.AND);
operator = Operator.AND;
}
case "|" -> {
assertWellFormed(expression, operator == null || operator == Operator.OR);
operator = Operator.OR;
}本层⼀旦定了⼀个运算符,再来另⼀个就抛。
⽽这个解析器最漂亮的地⽅,是它的产物:
// [framework] spring-core/src/main/java/org/springframework/core/env/ProfilesParser.java:122
private static Profiles or(Profiles... profiles) { return activeProfile -> Arrays.stream(profiles).anyMatch(isMatch(activeProfile)); }
private static Profiles and(Profiles... profiles) { return activeProfile -> Arrays.stream(profiles).allMatch(isMatch(activeProfile)); }
private static Profiles not(Profiles profiles) { return activeProfile -> !profiles.matches(activeProfile); }
private static Profiles equals(String profile) { return activeProfile -> activeProfile.test(profile); }没有 AST 节点类,没有 visitor,没有 evaluate(Node) 。解析产物就是⼀串嵌套的闭包。 "(a & b) | !c" 被"编译"成⼀棵 lambda 树,求值就是调⼀次 matches(predicate) ,它⾃⼰往下问⼀路。零反射、零分派、零中间对象。
再看这⼀句:
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractEnvironment.java:397
public boolean acceptsProfiles(Profiles profiles) {
Assert.notNull(profiles, "Profiles must not be null");
return profiles.matches(this::isProfileActive);
}✨ 职责切得⼲⼲净净: Profiles 只管布尔逻辑,"某个名字算不算激活"永远由 Environment ⽤⼀个 Predicate<String> 注⼊进去。 这个切分的回报在第 7.5 节会看到——
Boot 可以在完全没有 Environment 的地⽅复⽤这套表达式引擎。
7.3 @Profile 就是⼀个 Condition// [framework] spring-context/src/main/java/org/springframework/context/annotation/ProfileCondition.java:36
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;
}
@Profile 注解本身( [framework] spring-context/src/main/java/org/springframework/context/annotation/Profile.java:110 )只是
@Conditional(ProfileCondition.class) 。它⾛的是 @Conditional 那套基础设施,没有任何特殊待遇。⽽它调的是 matchesProfiles ——也就是 Profiles.of(...)那套表达式引擎,所以 @Profile("!prod & !test") 完全合法。
7.4 反直觉的⼀条:在 Spring Boot ⾥, Environment 根本不读 spring.profiles.active上⾯ 7.1 讲的那套"懒读属性"机制,在 Boot ⾥被彻底关掉了。整个类只有三个⽅法:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/ApplicationEnvironment.java:31
class ApplicationEnvironment extends StandardEnvironment {@Override
protected @Nullable String doGetActiveProfilesProperty() {
return null;
}@Override
protected @Nullable String doGetDefaultProfilesProperty() {
return null;
}@Override
protected ConfigurablePropertyResolver createPropertyResolver(MutablePropertySources propertySources) {
return ConfigurationPropertySources.createPropertyResolver(propertySources);
}
}⼀个包私有类,48 ⾏,两个 return null 加⼀个⼯⼚覆写。
两个 return null ⼲掉了整条祖传的⾃动读表路径。 在 Boot ⾥,profile 的最终值是 config data 那⼀整套流程算完之后,⽤ environment.setActiveProfiles(...) 显式灌
进去的( [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironment.java:350 ⼀带)。为什么要这么做?因为 Boot 的 profile 计算复杂得多:要考虑 spring.profiles.include 、 spring.profiles.group 、 SpringApplication.setAdditionalProfiles ,还要处理"profile 本身可能来⾃⼀个 profile-specific ⽂件"的⾃举问题。留着基类那条懒读路径,只会让状态在计算完成之前就被提前冻结(7.1 讲过,读⼀次就定死)。
✨ 我认为这是整个继承体系⾥最克制、也最有效的⼀次覆写:不能改基类,那就把基类的钩⼦填空。 三⼗⾏不到,换来⼀整套新算法的落脚点。
⚠ 但代价要说清楚:Framework 和 Boot 在这⼀点上⾏为不同。 7.1 那条"profile 读⼀次就冻结"的暗礁,在纯 Framework 应⽤⾥成⽴,在 Boot ⾥不成⽴。你在⽹上读到的 profile
⽂章,九成没有区分这两种情形。
7.5 Boot 侧的三个补充其⼀, Type 枚举是理解 active/default 差异的钥匙:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/Profiles.java:227
ACTIVE (AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, Environment::getActiveProfiles, true, Collections.emptySet()),
DEFAULT(AbstractEnvironment.DEFAULT_PROFILES_PROPERTY_NAME, Environment::getDefaultProfiles, false, Collections.singleton("default"));第三个参数是 mergeWithEnvironmentProfiles :ACTIVE 是 true (编程式设的和配置⽂件⾥的会合并),DEFAULT 是 false (编程式设的直接覆盖)。这两个的⾏为不⼀样,⽽这件事我没在任何⼀处⽂档⾥⻅过。
spring.profiles.group 的展开是⼀次显式的栈式 BFS( :139-151 ),⽤ LinkedHashSet 去重,天然容忍环—— if (expandedProfiles.add(current)) 为假就不再往下展开,所以 a → b → a 不会栈溢出。
其⼆,⼀处很好的教学素材:
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataProperties.java:141
return org.springframework.core.env.Profiles.of(this.onProfile).matches(activeProfiles);这⾏为什么写全限定名?因为同⼀个⽂件⾥ Profiles 这个简单名,已经被 Boot ⾃⼰的 context.config.Profiles 占了。
Boot 有⼀个 Profiles 类,Framework 有⼀个 Profiles 接⼝,同名不同物。⽽ Boot 那个⽤的正是 Framework 这个的表达式引擎——这就是 7.2 结尾说的那个回报:因为
Profiles.matches 收的是 Predicate<String> ⽽不是 Environment , spring.config.activate.on-profile: "prod & !cn" 这种表达式在⼀个连 Environment 都还没定型的阶段就能求值。
其三,⼀条会让你启动失败的硬规矩。 [boot] core/spring-boot/src/main/java/org/springframework/boot/context/config/InvalidConfigDataPropertyException.java:51 起有⼀个 PROFILE_SPECIFIC_ERRORS 集合,把
spring.profiles.include 、 spring.profiles.active 、 spring.profiles.default (及各⾃的 [0] 形式)全列了进去:不能在 application-prod.yml ⾥写 spring.profiles.active 。
道理很直⽩:那是"我已经因为 prod 被激活,才轮到你被读进来,⽽你现在⼜想改激活列表"——⾃举悖论。Boot 没有在这⾥留⼀个⽞学 bug,⽽是做成了启动期硬失败。另有⼀组⽆条
件禁⽌的( :41-49 ): spring.profiles 这个属性名已被彻底废掉,必须改⽤ spring.config.activate.on-profile 。⼋、 ${} 是怎么被拆开的换到第⼆条主线。前⾯⼀直在讲"取⼀个值",现在讲"取到的值⾥还写着别的值"。
先澄清⼀件事: ${} 不是 Environment 的能⼒,是 PropertyResolver 的能⼒。 Environment 只是恰好也继承了 PropertyResolver ⽽已。
8.1 分⼯
AbstractPropertyResolver.resolvePlaceholders(text) :245 → nonStrictHelper(解不出就原样保留)
AbstractPropertyResolver.resolveRequiredPlaceholders(text) :253 → strictHelper(解不出就抛)↓ 都⾛
doResolvePlaceholders(text, helper) :285
= helper.replacePlaceholders(text, this::getPropertyAsRawString)↓PropertyPlaceholderHelper [framework] spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java:37↓ 现在只剩⼀个字段和两个重载,真正的⼯作全在
PlaceholderParser (包私有) [framework] spring-core/src/main/java/org/springframework/util/PlaceholderParser.java:61⚠ 本基线如此,⽽且这是⼀处必须点破的版本差异: PlaceholderParser 是 @since 6.2 新写的类。 PropertyPlaceholderHelper 如今只剩 private final
PlaceholderParser parser; ⼀个字段,⾃⼰什么都不做了。
⽹上所有讲" PropertyPlaceholderHelper.parseStringValue 怎么递归"的⽂章,描述的都是 6.2 之前的实现。那个⽅法在本基线⾥已经不存在了。
8.2 ⼀个⽅法名切开了两个关注点doResolvePlaceholders 传给引擎的回调是 this::getPropertyAsRawString 。⽽:
// [framework] spring-core/src/main/java/org/springframework/core/env/PropertySourcesPropertyResolver.java:69@Override
protected @Nullable String getPropertyAsRawString(String key) {
return getProperty(key, String.class, false); // ←第三个参数 false
}false 就是第⼀节那个 resolveNestedPlaceholders 。
占位符引擎从属性源拿到的,永远是"未展开的原始值";展开的活⼉,由引擎⾃⼰统⼀负责。
如果不这样,就会出现"resolver 先展开⼀层、parser 再展开⼀层"的双重解析——转义符会被吃两次,默认值语义会乱, ${a:${b}} 这种写法的结果会变得不可预测。⼀个⽅法名,把"取值"和"展开"两个关注点彻底切开了。
8.3 三段式与⼀处⼏乎⽆⼈知晓的两次尝试
PlaceholderParser 把字符串切成 List<Part> ,三种实现: TextPart (纯⽂本)、 SimplePlaceholderPart ( ${key:default} ,key ⾥没有嵌套)、
NestedPlaceholderPart (key 或 default ⾥还有占位符)。SimplePlaceholderPart.resolve 是标准三段式:
// [framework] spring-core/src/main/java/org/springframework/util/PlaceholderParser.java:497@Override
public String resolve(PartResolutionContext resolutionContext) {
String value = resolveRecursively(resolutionContext);
if (value != null) {
return value; //① 查到了
}
else if (this.fallback != null) {
return this.fallback; //② ⽤ ${k:default}的默认值
}

return resolutionContext.handleUnresolvablePlaceholder(this.key, this.text); //③ 交给策略
}
第 ③ 步分两种策略:宽松模式原样吐回 ${key} ;严格模式抛 PlaceholderResolutionException ( [framework] spring-core/src/main/java/org/springframework/util/PlaceholderResolutionException.java:34 , @since 6.2 , extends IllegalArgumentException ——所以⽼的
catch (IllegalArgumentException) 代码仍然⼯作)。但真正有意思的是紧挨着的这⼀段:
// [framework] spring-core/src/main/java/org/springframework/util/PlaceholderParser.java:509
private String resolveRecursively(PartResolutionContext resolutionContext) {
if (!this.text.equals(this.key)) {
String value = resolveRecursively(resolutionContext, this.text);
if (value != null) {
return value;
}
}
return resolveRecursively(resolutionContext, this.key);
}有默认值时, text 是 "k:def" , key 是 "k" 。这段代码先拿整串 "k:def" 当属性名查⼀次,查不到才拿 "k" 查、再回退默认值。
🦴 所以 ${a:b} 会先试属性名字⾯量 "a:b" 。
这让"属性名⾥本来就带冒号"的情况仍然可以被显式配置命中——⽐如你有⼀个 key 真的叫 jdbc:mysql ,或者 Windows 路径⾥的 C: 。这是⼀个⼏乎⽆⼈知晓、但会实实在在影响⾏为的细节:如果某天你发现 ${foo:bar} 没有取到默认值 bar ,先去看看是不是真有⼈配了⼀个叫 foo:bar 的属性。
8.4 循环检测是"路径栈"不是"访问集"
// [framework] spring-core/src/main/java/org/springframework/util/PlaceholderParser.java:358
if (!this.visitedPlaceholders.add(placeholder)) {
throw new PlaceholderResolutionException(
"Circular placeholder reference '%s'".formatted(placeholder), placeholder, null);
}
visitedPlaceholders 是懒建的 HashSet<>(4) ,⽽且⽤完即 remove ( :368-372 )。这个 remove 很关键:它让这个集合是路径栈语义,⽽不是"访问过就不能再访问"。同⼀个 key 在两个不同的分⽀⾥各出现⼀次,是完全合法的——只有沿着同⼀条解析路径回到⾃⼰,才算循环。
8.5 ⚠ ⼀个 JVM 参数能改变全应⽤的占位符语义AbstractPropertyResolver 的默认值全表(已回源核实):
字段 ⾏ 默认值
ignoreUnresolvableNestedPlaceholders :94 false (默认严格)
placeholderPrefix :96 "${"
placeholderSuffix :98 "}"valueSeparator :100 ":"
escapeCharacter :102 '\'requiredProperties :104 空集前四个来⾃ [framework] spring-core/src/main/java/org/springframework/util/SystemPropertyUtils.java:39/42/45 , escapeCharacter 来⾃同⽂件
:51 ( @since 6.2 )。转义功能本身是 @since 6.2 才有的。 6.2 之前根本没有 \${...} 这回事,你想让 ${} 原样输出只能靠别的招。写⽂档、写规范时如果⾯向的是 Boot 3 ⽤户,这⼀条要交代版本⻔槛。
⽽更值得警惕的是这个默认值可以被全局改掉:
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java:341
public static @Nullable Character getDefaultEscapeCharacter() throws IllegalArgumentException {
Character escapeCharacter = defaultEscapeCharacter;
if (UNDEFINED_ESCAPE_CHARACTER.equals(escapeCharacter)) {
String value = SpringProperties.getProperty(DEFAULT_PLACEHOLDER_ESCAPE_CHARACTER_PROPERTY_NAME);
if (value != null) {
if (value.isEmpty()) {// Disable escape character support by default.
escapeCharacter = null;
}
else if (value.length() == 1) { ... }
else { throw new IllegalArgumentException(...); }
}
else {
escapeCharacter = SystemPropertyUtils.ESCAPE_CHARACTER;
}
defaultEscapeCharacter = escapeCharacter; // ←缓存进 static volatile
}
return escapeCharacter;
}
属性名是 spring.placeholder.escapeCharacter.default ( :66-67 ),可来⾃ JVM system property,也可来⾃ classpath 根下的 spring.properties 。设成空串 → 转义整个禁⽤;
设成单字符 → 换成那个字符;
多字符或 Character.MIN_VALUE → 抛异常。
⼀个 -D 参数,就能改变全应⽤所有占位符的转义语义。 ⽽且结果被缓存在 static volatile Character defaultEscapeCharacter ( :83 )⾥,第⼀次读过之后就再也不会变。
🦴 这⾥还有⼀个⼩设计值得看:哨兵值⽤的是 UNDEFINED_ESCAPE_CHARACTER = Character.MIN_VALUE ,⽽不是 null 。为什么?因为 null 在这⾥是⼀个合法的返回值(表
示"禁⽤转义"),所以不能拿 null 当"尚未初始化"。这是"⽤ null 表达业务含义"之后必然要付的⼀笔账。
九、 PropertySourcesPlaceholderConfigurer :那⼀⾏才是 @Value 能⼯作的原因
[framework] spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java ( @since 3.1 )是⼀个BeanFactoryPostProcessor——⽤坊⾥的话说,是"改图纸的⼈"。它在开造之前,把所有图纸上写着 ${} 的地⽅,替换成真值。
// [framework] spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java:129
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.propertySources == null) {
this.propertySources = new MutablePropertySources();
if (this.environment != null) {
PropertySource<?> environmentPropertySource =
(this.environment instanceof ConfigurableEnvironment configurableEnvironment ?
new ConfigurableEnvironmentPropertySource(configurableEnvironment) :
new FallbackEnvironmentPropertySource(this.environment));
this.propertySources.addLast(environmentPropertySource); // :138
}
PropertySource<?> localPropertySource =
new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
if (this.localOverride) { this.propertySources.addFirst(localPropertySource); } // :144
else { this.propertySources.addLast(localPropertySource); } // :147
}
processProperties(beanFactory, createPropertyResolver(this.propertySources)); // :155
this.appliedPropertySources = this.propertySources;
}
两个源名常量: "environmentProperties" ( :81 )、 "localProperties" ( :75 )。三条要点:
localOverride 默认 false ( [framework] spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderSupport.java:49 )。类javadoc :53-56 说得很明⽩:"which is by default false meaning that local properties are to be searched last, after all environment property sources."你setLocations 加的那个 properties ⽂件,优先级⽐ Environment 低。
⼀旦调了 setPropertySources(...) ,environment 和 local properties 全部被忽略。 javadoc :125-127 ⽤了加粗:"If setPropertySources is called,environment and local properties will be ignored"。
createPropertyResolver ( :165 , @since 6.0.12 )是可覆写钩⼦。9.1 那⼀⾏
processProperties ( :173 )先把配置项灌进 resolver(prefix / suffix / valueSeparator / escapeCharacter, :176-179 ),再组装⼀个 StringValueResolver :// [framework] spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java:181
StringValueResolver valueResolver = strVal -> {
String resolved = (this.ignoreUnresolvablePlaceholders ?
propertyResolver.resolvePlaceholders(strVal) :
propertyResolver.resolveRequiredPlaceholders(strVal));
if (this.trimValues) {
resolved = resolved.trim();
}
return (resolved.equals(this.nullValue) ? null : resolved);
};
doProcessProperties(beanFactoryToProcess, valueResolver);
PlaceholderConfigurerSupport 的默认值( [framework] spring-
beans/src/main/java/org/springframework/beans/factory/config/PlaceholderConfigurerSupport.java ,已回源核实): trimValues = false ( :129 )、 nullValue⽆值( :131 ,即没有哪个字符串会被当成 null)、 ignoreUnresolvablePlaceholders = false ( :133 ,默认严格,解不出就炸)。
然后 doProcessProperties ( :238-263 )做三件事:
1. ⽤ BeanDefinitionVisitor 遍历所有 BeanDefinition 替换 ${} ——顺便跳过⾃⼰那份 definition,注释写着 "to avoid failing on unresolvable placeholders in
properties file locations";
2. beanFactoryToProcess.resolveAliases(valueResolver) ( :259 )——别名⾥也能写 ${} ,这条⼤概没⼏个⼈⽤过;
3. beanFactoryToProcess.addEmbeddedValueResolver(valueResolver) ( :262 )。第三条就是本节的标题。 @Value 之所以能⼯作,不是因为 @Value 这个注解有什么魔法,⽽是因为这⼀⾏把⼀个 lambda 塞进了 BeanFactory 的 embeddedValueResolvers列表。下⼀节会看到它是怎么被取出来⽤的。
9.2 ⚠ 同⼀段 @Value ,在两种配置下⾏为完全不同如果⼀个纯 Framework 应⽤没有注册任何 configurer 呢?
// [framework] spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java:961// Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}容器在 finishBeanFactoryInitialization ⾥补了⼀个兜底。所以 @Value("${...}") 即使不注册任何 configurer 也能⽤。但请注意它⽤的是 resolvePlaceholders ——宽松模式。
有 configurer 时, @Value("${nonexistent}") 抛异常;没有 configurer 时,它被原样注⼊成字符串 "${nonexistent}" 。同⼀段业务代码,⼀个配错了的 key,⼀边是启动期硬失败,⼀边是运⾏到某个分⽀才发现某个字段的值是⼀坨 ${...} 。这两种⾏为的差距,⼤到不该由"你有没有恰好注册过⼀个BFPP"来决定。
Boot ⽤户不会遇到这个问题,因为 Boot ⼀定给你配好:
// [boot] core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/context/PropertyPlaceholderAutoConfiguration.java:36@AutoConfiguration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public final class PropertyPlaceholderAutoConfiguration {@Bean
@ConditionalOnMissingBean(search = SearchStrategy.CURRENT)
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}注意两处: @AutoConfigureOrder(HIGHEST_PRECEDENCE) ——它要最早跑; search = SearchStrategy.CURRENT ——只看当前容器,⽗容器⾥有不算,这样⽗⼦容器各有⼀份。
还有那个 static 。如果你⾃⼰⼿写这个 @Bean ,⽅法必须是 static 的。 因为它是 BFPP,需要在很早的阶段被造出来,⾮ static 会导致整个 @Configuration 类被提前实例
化(那个类上的 @Autowired 、 @Value 都还没来得及处理)。 [framework] spring-context/src/main/java/org/springframework/context/annotation/PropertySource.java:69-76 的 javadoc 专⻔讲了这件事,并顺便说明:显式注册这个 configurer "istypically only required if you need to customize configuration such as the placeholder syntax"。
9.3 ✨ ⼀处 @since 6.2.7 的精妙修补// [framework] spring-context/src/main/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.java:227
private static class ConfigurableEnvironmentPropertySource extends PropertySource<ConfigurableEnvironment> {...@Override// Declare String as covariant return type, since a String is actually required.
public @Nullable String getProperty(String name) {
for (PropertySource<?> propertySource : super.source.getPropertySources()) {
Object candidate = propertySource.getProperty(name);
if (candidate != null) {
return convertToString(candidate);
}
}
return null;
}
}
看仔细:它遍历的是 environment 内部的 PropertySources ,⽽不是直接调 environment.getProperty(name) 。为什么绕这⼀圈?因为 environment.getProperty(name) 会⾃⼰再解析⼀遍嵌套占位符(第⼀节那个 :82-90 ),⽤的是 environment ⾃⼰的前后缀 / 转义符设置——⽽不是你在 configurer 上配的那⼀套。
绕过它,就保证了:
占位符只被解析⼀次,且只按 configurer 的规则解析。
这是⼀个很⼩、很晚(6.2.7)才补上的洞,但它体现了⼀个原则:当⼀个组件允许你定制语法,它就必须确保这套语法是全链路唯⼀⽣效的那套。 半路杀出⼀个⽤默认语法解析过⼀遍的中间层,是最难查的那类 bug。
旁边还有个 FallbackEnvironmentPropertySource ( :284 ,同样 @since 6.2.7 ),给"拿到的 Environment 不是 ConfigurableEnvironment "兜底。它的 javadoc ⾃⼰都写着 "Should never apply in a regular scenario"。
⼗、 @Value 的完整求值链路把前⾯所有零件串起来。六步,每⼀步都有坐标。
① 注册解析器第九节的 PlaceholderConfigurerSupport:262 把 lambda 塞进这⾥:
// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java:151/** String resolvers to apply, for example, to annotation attribute values. */
private final List<StringValueResolver> embeddedValueResolvers = new CopyOnWriteArrayList<>();② 取出 @Value 的字⾯量// [framework] spring-beans/src/main/java/org/springframework/beans/factory/annotation/QualifierAnnotationAutowireCandidateResolver.java:67
private Class<? extends Annotation> valueAnnotationType = Value.class;// :411
public @Nullable Object getSuggestedValue(DependencyDescriptor descriptor) {
Object value = findValue(descriptor.getAnnotations());
if (value == null) {MethodParameter methodParam = descriptor.getMethodParameter();
if (methodParam != null) {
value = findValue(methodParam.getMethodAnnotations());
}
}
return value;
}三个细节:
先查参数/字段上的注解,再查⽅法上的注解——所以 @Value 打在 setter ⽅法上也有效。
findValue ( :425 )⽤的是 AnnotatedElementUtils.getMergedAnnotationAttributes ,⽀持元注解组合。你可以造⼀个 @MyDbUrl ,身上标着
@Value("${db.url}") ,然后到处⽤ @MyDbUrl 。:67 那个字段说明注解类型是可替换的—— @Value 并没有被硬编码死。
③④⑤ 三⾏代码定死了顺序// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java:1675// Step 2: pre-defined value or expression, for example, from @Value
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
if (value instanceof String strValue) {
String resolvedValue = resolveEmbeddedValue(strValue); // ← ${}在这⾥
BeanDefinition bd = (beanName != null && containsBean(beanName) ?
getMergedBeanDefinition(beanName) : null);
value = evaluateBeanDefinitionString(resolvedValue, bd); // ← #{}在这⾥
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
try {
return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
}...
}${} 永远先于 #{} ,⽽且是硬编码的先后,不是什么优先级配置。
这⼀条是⽆数⾯试题和线上事故的答案:
@Value("#{'${my.list}'.split(',')}") 能⼯作——先把 ${my.list} 换成字⾯量,得到 #{'a,b,c'.split(',')} ,再交给 SpEL。反过来 @Value("${#{...}}") 不⾏——轮到 ${} 的时候, #{} 还是原样的字符串, ${#{...}} 会被当成⼀个名字⾥带 #{ 的属性去查。
${} 的执⾏:
// [framework] spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java:966
public @Nullable String resolveEmbeddedValue(@Nullable String value) {
if (value == null) {
return null;
}
String result = value;
for (StringValueResolver resolver : this.embeddedValueResolvers) {
result = resolver.resolveStringValue(result);
if (result == null) {
return null;
}
}
return result;
}🦴 多个 resolver 是串联的——前⼀个的输出喂给后⼀个,不是"谁先返回⾮空谁赢"。所以注册两个 configurer 时,占位符会被依次处理两轮。⽽任何⼀环返回 null 就⽴即短路
——这正好接上第九节那个 resolved.equals(this.nullValue) ? null : resolved : nullValue 机制就是在这⾥落地成"这个依赖注⼊ null"的。
#{} 的执⾏在 evaluateBeanDefinitionString ( :1662 ),先看有没有 beanExpressionResolver ,没有就原样返回。默认实现的前后缀是 "#{" / "}" ( [framework]
spring-context/src/main/java/org/springframework/context/expression/StandardBeanExpressionResolver.java:72,75 )。⑥ 类型转换,⽽且是另⼀条链
最后⼀⾏ converter.convertIfNecessary(...) ⽤的是 BeanFactory 的 TypeConverter 。⚠ 这不是 PropertyResolver 的 ConversionService 。 两者是两条完全独⽴的转换链:
@Value("${port}") int port —— 字符串转 int 发⽣在 DefaultListableBeanFactory:1686 ,⾛ BeanFactory 的 TypeConverter (受
CustomEditorConfigurer 、 ConversionService bean 等影响)。
environment.getProperty("port", Integer.class) —— ⾛ AbstractPropertyResolver.convertValueIfNecessary ( :298 )。两条链的可⽤转换器可能不同。你给容器注册了⼀个⾃定义 Converter , @Value 认, environment.getProperty(key, MyType.class) 未必认。
🦴 顺带看⼀眼第⼆条链的懒加载,它写得很讲究:
// [framework] spring-core/src/main/java/org/springframework/core/env/AbstractPropertyResolver.java:298
protected <T> @Nullable T convertValueIfNecessary(Object value, @Nullable Class<T> targetType) {
if (targetType == null) {
return (T) value;
}
ConversionService conversionServiceToUse = this.conversionService;
if (conversionServiceToUse == null) {// Avoid initialization of shared DefaultConversionService if// no standard type conversion is needed in the first place...
if (ClassUtils.isAssignableValue(targetType, value)) {
return (T) value;
}
conversionServiceToUse = DefaultConversionService.getSharedInstance();}
return conversionServiceToUse.convert(value, targetType);
}
getProperty(key, String.class) 这条最热的路径,完全不碰 ConversionService ,也不会把那个巨⼤的共享实例初始化出来。 取 String 出 String, isAssignableValue直接放⾏。
⽽ getConversionService() ( :108 )那边则⽤双检锁建了⼀个独⽴的 DefaultConversionService ,代码注释( :109-110 )特意说明:"Need to provide an independentDefaultConversionService , not the shared DefaultConversionService used by PropertySourcesPropertyResolver ."
同⼀个类⾥,两个⽅法,⽤了两个不同的 ConversionService 实例。 这不是笔误,是刻意的—— getConversionService() 返回的那个是给外部拿去改的(它的返回类型是
ConfigurableConversionService ),不能是全局共享的那个。⼗⼀、Boot 的翻译官,坐第⼀位最后回到 Boot。第四节说过,Framework 的宽松名字查找只属于 systemEnvironment ⼀个源。可实际写 Boot 的⼈都知道, server.port 、 SERVER_PORT 、 server-port好像到处都能⽤。
答案是 Boot 在账本最上⾯⼜加了⼀本账,⽽这本账⾥⼀条记录都没有。
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/ConfigurationPropertySources.java:89
public static void attach(Environment environment) {
Assert.isInstanceOf(ConfigurableEnvironment.class, 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 )。在 actuator /env ⾥排在第⼀位的那个,就是它。它是⼀个假源:内部持有的 SpringConfigurationPropertySources 包的是同⼀个 sources 列表的视图。查询时,它把 key 当成 ConfigurationPropertyName 做松散匹配,再回头去问后⾯那些真账本。
它必须坐第⼀位,否则翻译就晚了。
那它遍历那个列表时,会不会问到⾃⼰?
// [boot] core/spring-boot/src/main/java/org/springframework/boot/context/properties/source/SpringConfigurationPropertySources.java:135
private boolean isIgnored(PropertySource<?> candidate) {
return (candidate instanceof StubPropertySource
|| candidate instanceof ConfigurationPropertySourcesPropertySource);
}遍历时跳过⾃⼰,以及所有桩源。 前者防⽆限递归,后者是因为桩源永远返回 null,问了也⽩问。
SpringApplication.prepareEnvironment ⾥调了 attach 两次( :355 和 :366 ,后者是给"environment 可能被转换过"的情形)。为什么调两次没事?因为第⼆节讲过——addFirst 天⽣幂等,同名源重复 add 只是"移动"。这条性质在这⾥兑现了。
取值的快⻋道第三节留了个悬念: ApplicationEnvironment 覆写 createPropertyResolver 换掉了什么?换成了这个:
// [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 =宽松,不合法就返回 null
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);
}两条路:能翻译成合法 ConfigurationPropertyName 的,⾛松散绑定快⻋道;翻译不了(或者压根没 attach)的,回落到内嵌的 DefaultResolver ——那是⼀个PropertySourcesPropertyResolver 的⼦类,也就是第⼀节那个经典线性扫。
所以在 Boot ⾥, environment.getProperty("SERVER_PORT") 能⼯作,⽽且不只是环境变量那⼀个源⽀持。 这和第四节那条 Framework 事实不同。别混。
⽽这条快⻋道存在的另⼀个理由是性能。第⼀节那个 for 循环没有任何缓存——每次 getProperty 都从头线性扫⼀遍所有源。Boot 启动完成后, Environment ⾥常有⼗⼏个源,每问⼀个 key 就是⼗⼏次 map 查找,⽽绑定 @ConfigurationProperties 时要问的 key 是成百上千的。
我得说⼀句不那么客⽓的话:Boot 之所以要建这⼀整套 ConfigurationPropertySource 体系,⼀半是为了松散绑定,另⼀半是因为 Framework 那个抽象层"只有语义、没有索引"。 ⼀个抽象不够⽤,于是在它上⾯⼜坐了⼀个抽象,⽽且这个新抽象必须永远排在第⼀位才⽣效。这不是坏设计——它在兼容性约束下已经是最优解了——但它确实让"⼀个 key到底从哪来"这个问题的链路,⼜⻓了⼀截。
replace 保位次的⼀次漂亮兑现// [boot] core/spring-boot/src/main/java/org/springframework/boot/support/SystemEnvironmentPropertySourceEnvironmentPostProcessor.java:68
private void replacePropertySource(ConfigurableEnvironment environment, String sourceName,
PropertySource<?> propertySource, @Nullable String environmentPrefix) {
Map<String, Object> originalSource = (Map<String, Object>) propertySource.getSource();
SystemEnvironmentPropertySource source = new OriginAwareSystemEnvironmentPropertySource(sourceName,
originalSource, environmentPrefix);
environment.getPropertySources().replace(sourceName, source);
}把 "systemEnvironment" 整个换成⼀个 OriginAwareSystemEnvironmentPropertySource 。因为 replace 保位次(第⼆节),换完之后环境变量的优先级⼀点没变,只是每个值多带了⼀个 "origin"。
✨ 这就是 Boot 报错能说出"这个值来⾃ application-prod.yml 第 12 ⾏"的底层机制。 ⽽它能这么做,只是因为 PropertySource.equals 只⽐名字。
⚠ ⼀处必须交代的⽬录事实:这个类在 [boot] core/spring-boot/src/main/java/org/springframework/boot/support/ 下,不在 org.springframework.boot.env 下
——Boot 4 做过⼀次包重组, spring.factories ⾥那⼏个 EnvironmentPostProcessor 现在都指向 org.springframework.boot.support.* ,⽽RandomValuePropertySource 本身仍留在 org.springframework.boot.env 。搬⾛的是 EnvironmentPostProcessor ,不是 PropertySource ,这两个包别写混。
(⼀个可以拿来当侦查⼿法的痕迹: RandomValuePropertySourceEnvironmentPostProcessor 的类 javadoc 标 @since 4.0.0 ,它的构造器却标 @since 3.0.0 。"类是新的、成员是旧的"是包移动的典型指纹。本仓浅克隆⽆ git 历史,这类推断只能靠 @since 标签,不能假装查过 blame。)
⼗⼆、 @PropertySource :⼀个⾃带"请勿依赖"说明书的注解
最后⼀⼩节,收个尾。处理链是 ConfigurationClassParser ( [framework] spring-
context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java:314-325 )→ PropertySourceRegistry ( @since 6.0 )→PropertySourceProcessor 。落位逻辑在:
// [framework] spring-core/src/main/java/org/springframework/core/io/support/PropertySourceProcessor.java:127
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(newSource); //新的先
composite.addPropertySource(existing); //旧的后
propertySources.replace(name, composite); //原地换,位次不变// :136起
if (this.propertySourceNames.isEmpty()) {
propertySources.addLast(propertySource); //第⼀个:垫底
}
else {
String lastAdded = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
propertySources.addBefore(lastAdded, propertySource); //后续:插在上⼀个之前
}两条规则都指向同⼀个结论——后处理的赢:同名的会合成 CompositePropertySource 且新的排前⾯( CompositePropertySource.getProperty 同样是"第⼀个⾮ null 赢");不
同名的⽤ addBefore(lastAdded, ...) 插在前⼀个之前。注解 javadoc 的原话是 "the last @PropertySource annotation processed will 'win'"。紧接着 :144-145 ,官⽅⾃⼰写下了这本书⾥我最想引⽤的⼀句:
"if the @Configuration classes above were registered via component-scanning, the ordering is difficult to predict. In such cases ... it is recommended that theuser fall back to using the programmatic PropertySource API."
Spring 官⽅在⾃⼰的注解⽂档⾥,劝你别依赖这个注解的覆盖顺序。 ⼀个⽤来表达"配置从哪来"的注解,⾃带⼀份"顺序不可预测,请改⽤编程式 API"的说明书。再叠上 Boot ⽂档那
条(表 A 第 2 ⾏):这些源要到 context refresh 时才进 Environment ,对 logging.* 和 spring.main.* 已经太晚。我的结论很直接:在 Spring Boot 应⽤⾥, @PropertySource ⼏乎没有正当⽤途。 要么⽤ config data( spring.config.import 能⼲它能⼲的⼀切,⽽且时机正确、位次可预测),要么写⼀个 EnvironmentPostProcessor ⾃⼰ addFirst / addAfter 。⽤它只是把⼀个可预测的问题,换成了⼀个不可预测的问题。
🦴 两个收尾细节:位置串⾛的是严格解析( PropertySourceProcessor:90 的 resolveRequiredPlaceholders ),所以
@PropertySource("classpath:/com/${my.placeholder:default/path}/app.properties") ⽀持,但解不出就抛,除⾮ ignoreResourceNotFound=true ——⽽这个开关只
吞 FileNotFoundException / UnknownHostException / SocketException 三种( :160-164 )。另外, @PropertySource 在 AOT / native 下不靠运⾏期扫注
解: PropertySourceRegistry 把每个注解攒成 PropertySourceDescriptor record( @since 6.0 ), ConfigurationClassPostProcessor:499 取⾛,在 :704 ⼀带⽣成代码——构建期写死描述符,运⾏期重放。
🦴 ⻣灰级细节
- PropertySource.equals 只⽐名字( PropertySource.java:141 ),这⼀个决定同时买到了:按名字操作位次、 replace 保位次、重复 add 变"移动"、桩源可以先占位后换真身。
- StubPropertySource 是⼀个永远返回 null 的假账本,存在的唯⼀意义是把位次占住(位次是契约,内容是实现);⽽ ComparisonPropertySource 更极端——除
equals / hashCode / toString 外全抛 UnsupportedOperationException ,它只为被 List.indexOf() ⽐较⽽⽣。- MutablePropertySources ⽤ COW 容器 + synchronized 写操作,前者防 ConcurrentModificationException ,后者保"先 remove 再 add"的原⼦性。
4. AbstractEnvironment 从 :495 到 :588 近百⾏全是⼀⾏转发,它⾃⼰不是 resolver,是个柜台。 createPropertyResolver ( @since 5.3.4 )这个钩⼦ Framework⾃⼰⼀次都没⽤,是专⻔给 Boot 留的⻔。
- customizePropertySources 在构造函数⾥被调,⼦类实例字段此刻还没赋初值,读了就 NPE(javadoc :226-235 有专⻔警告)。
- SystemEnvironmentPropertySource 的⼤写⽤ Locale.ROOT ,躲开⼟⽿其语 locale 的 i → İ 陷阱。
- getPropertyAsRawString 传 resolveNestedPlaceholders=false ,⼀个⽅法名切开了"取值"与"展开占位符"两个关注点,避免双重解析。
- ${a:b} 会先拿字⾯量 "a:b" 当属性名查⼀次( PlaceholderParser:509-517 ),查不到才拆成 key + 默认值。占位符的循环检测则是路径栈语义(⽤完即 remove ),同⼀个 key 在不同分⽀各出现⼀次合法。
- getDefaultEscapeCharacter 的哨兵值是 Character.MIN_VALUE ⽽不是 null ,因为 null 在这⾥是"禁⽤转义"的合法值。
10. convertValueIfNecessary ⾛ isAssignableValue 快路径,取 String 这条最热路径完全不初始化 ConversionService ;⽽ getConversionService() 另建⼀个独⽴实例,因为那个是要给外部改的。
- resolveEmbeddedValue ⾥多个 StringValueResolver 是串联的,不是"谁先返回⾮空谁赢";任何⼀环返回 null ⽴即短路( nullValue 机制在这⾥落地)。顺
带, doProcessProperties 还做了 resolveAliases(valueResolver) ——bean 别名⾥也能写 ${} 。- Boot 的 profile 优先级不靠排序,靠遍历顺序: ContributorIterator 先吐 AFTER 阶段、再吐 BEFORE、最后吐⾃⼰;配合⼀路 addLast ,profile-specific ⽂件⾃然排在前⾯。
- .properties 压 .yml 是四次⽅向翻转的净结果,源码⾥没有任何⼀处写着这个意图;⽽同⼀个 YAML ⽂件⾥靠后的 --- 段优先级更⾼,靠ConfigDataEnvironmentContributors:183 ⼀⾏倒序循环实现。
⚠ 暗礁
- 空串会赢。 判据是 value != null ( PropertySourcesPropertyResolver:81 )。⾼优先级源⾥的 foo= 会彻底屏蔽低优先级源⾥的 foo=real ,⽽且没有任何⽇志会告诉你—— logKeyFound ⾃ 4.3.3 起故意不打印值。
- 两套相反的⽅向叙述:源码/Framework ⽂档是"index 0 最⾼",Boot 参考⽂档是"后⾯覆盖前⾯"。看清楚你⼿上是哪⼀张表。
3. 纯 Framework ⾥ profile 读⼀次就冻结( AbstractEnvironment:274 的 if (this.activeProfiles.isEmpty()) );Boot ⾥不是( ApplicationEnvironment 两个return null 把这条路关了)。同⼀个 API,两套⾏为。
4. default profile 只在 active 集合完全为空时⽣效( AbstractEnvironment:410-411 )。激活任何⼀个⽆关 profile, @Profile("default") 全部熄⽕。- @Profile 表达式⾥ & 和 | 不加括号不能混⽤( ProfilesParser:82,86 ), "a & b | c" 直接抛。profile 名字本身也不许以 ! 开头、不许是空⽩、不许有空格( trimAllWhitespace 是全串去空⽩,会被⽆声吃掉)。
6. containsProperty 有两套语义: AbstractPropertyResolver:205-207 是 getProperty(key) != null , PropertySourcesPropertyResolver:47-56 是逐源问各
⾃的 containsProperty ,⽽ MapPropertySource 的实现是 source.containsKey(name) 。对"key 存在但 value 为 null"的 map,答案不⼀致。MapPropertySource 的 javadoc 明确要求你⾃⼰保证 map ⾥没有 null 值——这是⼀条⽤户必须遵守的隐性契约。
7. 没有 PropertySourcesPlaceholderConfigurer 时 ${} ⾛宽松模式( AbstractApplicationContext:964-966 ),解不出的占位符会被原样注⼊成字符串;有configurer 时默认严格,直接抛。同⼀段 @Value 代码,两种命运。
8. ${} 永远先于 #{} ,硬编码在 DefaultListableBeanFactory:1679 与 :1682 的先后⾥。- @Value 的类型转换⽤的是 BeanFactory 的 TypeConverter ,不是 PropertyResolver 的 ConversionService 。 两条链的可⽤转换器可能不同。
- \ 转义是 @since 6.2 才有的,⽽且默认值可被 spring.placeholder.escapeCharacter.default 全局改掉甚⾄禁⽤,结果缓存在 static volatile 字段⾥——第⼀次读过就不会再变。
11. 两个⼏乎没⼈知道的开关: spring.getenv.ignore=true 会让整条环境变量源变空( AbstractEnvironment:464 ,默认 false );⽽ getSystemProperties() 是活引⽤
( :440 ),运⾏期 System.setProperty ⽴刻⽣效。- environment.merge(parent) 的⽅向是"⽗的排在⼦的所有源之后",且同名时保⼦丢⽗( :469-474 )。追加⽗的 default profiles 之前还会先 remove("default") 。⽗⼦容器⾥的同名源调试⾮常反直觉。
- 每次 getProperty 都是全量线性扫,没有缓存( PropertySourcesPropertyResolver:75 );⽽这次遍历看到的是 COW 快照,并发改动期间是"某⼀瞬间的列表"。
14. 不能在 profile-specific ⽂档⾥写 spring.profiles.active / default / include ( InvalidConfigDataPropertyException:51-61 ),启动期硬失败; spring.profiles 这个属性名已被彻底禁⽤。
15. @PropertySource 的相对顺序在 component-scan 下不可预测(官⽅承认),且进 Environment 的时机太晚,对 logging.* / spring.main.* 来不及;它的ignoreResourceNotFound 也只吞 FileNotFoundException / UnknownHostException / SocketException 三种。
- 同⽬录下 .properties 永远压过 .yml / .yaml 。 混⽤两种格式⼏乎必然踩坑。
🎯 三句带⾛
1. "谁覆盖谁"不是规则,是位次。 PropertySourcesPropertyResolver.getProperty ( [framework] .../PropertySourcesPropertyResolver.java:73-100 )按列表顺序线性扫,第⼀个⾮ null 的值就赢,后⾯的源不再问。判据是 value != null ——空串会赢,⽽且⽇志⾥看不到值。 MutablePropertySources 的下标就是优先级,index0 最⾼;Boot 参考⽂档的清单⽅向相反(后⾯覆盖前⾯),排查前先确认⽅向。
2. profile 只是开关,⽽ Framework 和 Boot ⽤的是两套算法。 Framework 侧懒读 spring.profiles.active ⼀次就冻结, default 只在 active 完全为空时⽣效;Boot 侧
⽤ ApplicationEnvironment 的两个 return null ( [boot] core/spring-boot/.../ApplicationEnvironment.java:34-40 )把基类这条路关死,改由 config data算完后 setActiveProfiles 显式灌⼊。表达式引擎( Profiles / ProfilesParser )是共⽤的, & 与 | 不加括号不能混⽤。
3. @Value 的链路是: getSuggestedValue 取字⾯量 → resolveEmbeddedValue 跑 ${} → evaluateBeanDefinitionString 跑 #{} → TypeConverter 转类型
( [framework] .../DefaultListableBeanFactory.java:1676-1686 )。顺序是硬编码的, ${} 永远先于 #{} 。⽽ ${} 能⼯作的原因只有⼀⾏——
PlaceholderConfigurerSupport:262 的 addEmbeddedValueResolver ;没有 configurer 时容器会兜底注册⼀个宽松模式的( AbstractApplicationContext:964-966 ),解不出的占位符会被原样注⼊⽽不是报错。
承上启下账房这⼀章,我刻意绕开了两个东⻄,⽽且绕得很明显。
第⼀个是"⽂件是怎么找到的"。 这⼀章⾥出现了 classpath:/ 、 file:./config/*/ 、 optional:classpath:/ ,还有
@PropertySource("classpath*:/config/*.properties") ——那个多出来的星号( @PropertySource 的 javadoc :204 说 "As of Spring Framework 6.1, resourcelocation wildcards are also supported")。我⼀直在⽤这些字符串,却⼀次也没解释过:⼀个 classpath*: 前缀,凭什么能把散落在⼏⼗个 jar ⾥的同名⽂件全部扫出来? JVM 的
classloader 并不提供"列出某个包下所有资源"的能⼒, ClassLoader.getResources() 只能按精确路径找。那个通配符是 Spring ⾃⼰⾛ URL 协议、拆 jar 包、递归⽬录⼿⼯实现的。这套东⻄叫 Resource 与 ResourcePatternResolver ,它是本章、也是整个 Spring 的另⼀根隐形⽀柱——配置⽂件、类扫描、模板加载、静态资源,全都站在它上⾯。
第⼆个是类型转换。 本章两次撞上它,两次都躲开了。 environment.getProperty("port", Integer.class) ⾛⼀条链
( AbstractPropertyResolver.convertValueIfNecessary ,还带⼀个"取 String 不初始化共享实例"的懒加载⼩把戏); @Value("${port}") int port ⾛另⼀条链( DefaultListableBeanFactory:1686 的 TypeConverter )。同⼀个"字符串变成 int"的动作,在 Spring ⾥有两条独⽴的通路,可⽤的转换器可能不同。 为什么会有两条?
ConversionService 和上古的 PropertyEditor 是什么关系? GenericConverter 、 ConverterFactory 、 ConditionalConverter 这三个⻓得很像的接⼝各⾃解决什么
问题? List<Integer> 是怎么从 "1,2,3" 变出来的?⼀个管"字节从哪来",⼀个管"字节变成什么"。 这两件事合在⼀起,才让"你在 YAML ⾥写⼀⾏ timeout: 30s ,拿到⼿的是⼀个 Duration 对象"这件看似理所当然的事成⽴。
下⼀章,我们把这两根⽀柱⼀起拆开。