在 @SpringBootTest 中应将 SPRING_APPLICATION_JSON 放在哪里?
结论
SPRING_APPLICATION_JSON 是 Spring Boot 识别的内联 JSON 配置属性,也可以通过环境变量 SPRING_APPLICATION_JSON 设置;它不是要放进 src/test/resources 的文件名。使用 @SpringBootTest 时,可以直接通过测试属性传入:@SpringBootTest(properties = "spring.application.json={\"foo\":\"bar\"}")。也可以把它放在 JVM 系统属性、操作系统环境变量或测试运行配置中。如果只是测试环境配置,用 application-test.yml 或 application-test.properties 通常更直观。
原因
Spring Boot 会读取名为 spring.application.json 的属性,并把其中的 JSON 解析成属性源;环境变量 SPRING_APPLICATION_JSON 通过 relaxed binding 对应到这个属性。测试资源目录里的 spring.application.json 文件不会被自动当作这个属性加载,除非自己写代码读取它。
在 @SpringBootTest 中配置的方式
方式一:使用 @SpringBootTest 的 properties
适合配置量少、且只对当前测试类生效的 JSON:
@SpringBootTest(properties = {
"spring.application.json={\"feature\":{\"enabled\":true}}"
})
class FeatureFlagTest {
@Value("${feature.enabled}")
private boolean enabled;
@Test
void jsonPropertyIsLoaded() {
assertThat(enabled).isTrue();
}
}
Java 字符串中的 JSON 双引号需要转义。
方式二:使用 @TestPropertySource
@SpringBootTest
@TestPropertySource(properties = {
"spring.application.json={\"feature\":{\"enabled\":true}}"
})
class FeatureFlagTest {
// ...
}
方式三:通过系统属性或环境变量
在 IDE 的测试运行配置里设置 VM options:
-Dspring.application.json='{"feature":{"enabled":true}}'
或者设置环境变量:
SPRING_APPLICATION_JSON='{"feature":{"enabled":true}}' ./mvnw test
在 Maven Surefire 中也可以配置系统属性:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<spring.application.json>{"feature":{"enabled":true}}</spring.application.json>
</systemPropertyVariables>
</configuration>
</plugin>
环境变量名用 SPRING_APPLICATION_JSON,注解或系统属性里通常用 spring.application.json。
方式四:改用测试配置文件
如果只是测试配置,建议改用 profile 文件,不要把 JSON 塞进一个属性:
src/test/resources/application-test.yml
feature:
enabled: true
@SpringBootTest
@ActiveProfiles("test")
class FeatureFlagTest {
// ...
}
注意事项
SPRING_APPLICATION_JSON的值必须是合法 JSON;不同位置对引号和转义的写法不同。@SpringBootTest(properties = ...)的优先级较高,适合覆盖测试中的少量配置。- 不要把
SPRING_APPLICATION_JSON当成文件名;如果希望使用文件,请使用 Spring Boot 支持的配置文件格式(如 YAML/properties),并按 profile 加载。 - JSON 较大时,写在注解里不容易维护,优先考虑测试配置文件或统一管理环境变量。
备注:内容仅供参考。
