Spring Cloud Config客户端本地开发者配置优先级不生效问题
我的目标
启用Spring Cloud Config Server配置导入功能,同时支持开发者在本地机器加载可选的自定义属性配置文件,预期配置优先级符合图示要求。

我已基于org.springframework.cloud:spring-cloud-config-server:3.1.3搭建配置中心,主类添加@EnableConfigServer注解,直接调用配置中心接口可返回符合预期的结果,该服务用于为开发者本地运行环境提供通用环境配置。
$ curl http://localhost:8888/test-application/dev
{"name":"test-application","profiles":["dev"],"label":null,"version":null,"state":null,"propertySources":[{"name":"classpath:/cfg/test-application/application-dev.yml","source":{"server.port":1111}},{"name":"classpath:/cfg/test-application/application.yml","source":{"server.port":8000}}]}
其中localhost:8888为配置中心地址,test-application为客户端应用名(通过spring.application.name指定),传入的dev为客户端激活的profile(dev profile仅用于标识本地运行场景,无对应独立部署的开发环境)。
客户端配置
application.yml配置如下:
spring: application: name: test-application config: import: - configserver:http://localhost:8888 # <- 从配置中心拉取配置 - optional:file:/absolute/path/to/the/project/root/ # <- 加载本地路径下的可选额外配置
客户端使用的依赖如下:
org.springframework.boot:spring-boot-starter-web:2.7.0org.springframework.cloud:spring-cloud-starter-bootstrap:3.1.3org.springframework.cloud:spring-cloud-starter:3.1.3org.springframework.cloud:spring-cloud-starter-config:3.1.3
如上述接口返回结果所示,配置中心的基础application.yml配置server.port=8000,profile专属的application-dev.yml配置server.port=1111,参考Spring Boot官方文档该配置加载逻辑符合预期,但我在项目根目录放置的本地开发者配置文件中配置了server.port=2222,该值未生效。
问题现象
启动客户端应用时,可观测到如下日志:
Fetching config from server at : http://localhost:8888 Located environment: name=test-application, profiles=[default], label=null, version=null, state=null Located property source: [BootstrapPropertySource {name='bootstrapProperties-configClient'}, BootstrapPropertySource {name='bootstrapProperties-classpath:/cfg/test-application/application-dev.yml'}, BootstrapPropertySource {name='bootstrapProperties-classpath:/cfg/test-application/application.yml'}] The following 1 profile is active: "dev" Tomcat initialized with port(s): 1111 (http) Initializing Spring embedded WebApplicationContext Tomcat started on port(s): 1111 (http) with context path '' Started TestApplicationKt in 2.234 seconds (JVM running for 2.762)
Spring最终采用的端口配置为1111,而非预期中项目根目录下开发者配置application-dev.yml中设置的2222端口。
问题总结
共涉及三份配置文件:
- 配置中心存储的
application.yml(端口: 8000) - 配置中心存储的
application-dev.yml(端口: 1111) - 项目根目录的开发者本地配置
application-dev.yml(端口: 2222)<- 期望该文件优先级高于前两份配置
调试时发现,注入的Environment Bean中已识别到目标开发者配置文件,其中server.port=2222的属性值加载正确,但优先级低于配置中心返回的配置,因此未被采用。

寻求该问题的可行解决方案。
我已搭建可复现该问题的示例项目,GitHub示例项目地址。
提前感谢解答!
内容的提问来源于stack exchange,提问作者wartoshika

