You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot首个测试类读取非激活配置文件属性的原因排查

Spring Boot首个测试类读取非激活配置文件属性的原因排查

遇到这种情况确实挺挠头的——明明日志明明白白显示test profile已经激活了,结果第一个测试却偏偏读取了默认配置里的uat.internal地址,后面的测试又一切正常。我来结合你的场景拆解下问题的来龙去脉,以及你找到的关键解决点。

先还原你的问题场景

首先把你遇到的核心信息整理清楚:

  • 依赖版本:使用spring-boot-starter-parent:3.3.12
  • 测试配置:测试类ControllerIntegrationTests标注了@SpringBootTest + @ActiveProfiles("test")
  • 配置文件:
    • application.properties:notifications.url=http://uat.internal:8080
    • application-test.properties:notifications.url=http://localhost:8080
  • 日志与输出:
    日志明确显示第一个测试激活了test profile,但你的NotificationClient Bean打印的notifications.url却是默认配置的值;后续测试则正常读取到localhost的地址。

你的NotificationClient Bean代码:

@Bean
public NotificationClient notificationClient(@Value("${notifications.url}") String baseUrl, 
                                             @Value("${windows.username}") String username, 
                                             @Value("${windows.password}") String password) {
    String[] profiles = environment.getActiveProfiles();
    System.out.println("*** profiles: " + Joiner.on(",").join(profiles));
    System.out.println("*** notifications.url: " + environment.getProperty("notifications.url"));
    return new NotificationClient(baseUrl, username, password);
}

首次测试的关键日志片段:

2025-07-22T10:33:41.372+01:00 INFO 32896 --- [ main] [ ] u.c.f.primary.ControllerIntegrationTests : The following 1 profile is active: "test"
...
*** profiles: test
*** notifications.url: http://uat.internal:8080

问题根因:spring-boot-maven-plugin的隐性干扰

你提到去掉spring-boot-maven-plugin后问题消失,这恰恰是问题的核心。这个插件在和openapi插件配合使用时,会对mvn verify阶段的测试启动流程产生影响:

  1. 插件执行时机的冲突:spring-boot-maven-plugin的默认配置会在测试阶段参与类路径的处理,当它和openapi插件一起工作时,可能会在首次测试初始化前修改了类路径或者配置加载的上下文,导致Spring Boot的配置覆盖逻辑(profile配置优先于默认配置)没有正确触发。
  2. 首次测试的上下文异常:Spring Boot测试默认会复用上下文,但首次测试时因为插件的干扰,上下文初始化时错误地加载了默认配置;后续测试要么复用了修复后的上下文,要么插件的影响已经消除,所以能正确读取test profile的配置。

解决与优化方案

既然你已经通过移除插件解决了问题,如果之后需要重新引入spring-boot-maven-plugin(比如要保留打包功能),可以调整插件的执行阶段,让它只在打包时运行,不干扰测试:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
            <phase>package</phase> <!-- 只在package阶段执行,跳过测试阶段 -->
        </execution>
    </executions>
</plugin>

这种插件交互导致的配置问题确实比较隐蔽,好在你精准定位到了根源,调整插件配置就能兼顾功能和测试的正确性。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:03:04