如何仅针对develop配置文件覆盖外部credentials.properties的配置?
解决方案
方案一:通过IDE运行参数指定高优先级的Develop专属配置
这个方法无需修改代码,全程在IDE内操作:
- 在项目的
src/main/resources目录下创建application-develop-override.properties(文件名可自定义),写入需要覆盖的配置项,示例:
# 覆盖外部credentials.properties中的主密码 main.password=dev-local-password
- 打开IDE的Run/Debug Configurations,找到你的应用配置:
- 可以在VM options中添加:
也可以在Program arguments中添加:-Dspring.config.additional-location=classpath:application-develop-override.properties--spring.config.additional-location=classpath:application-develop-override.properties
- 可以在VM options中添加:
- 确保运行时激活
developprofile(可通过VM参数-Dspring.profiles.active=develop指定,或依赖项目原有构建变量)。
通过spring.config.additional-location指定的配置文件优先级高于外部的file:${user.home}/.app/credentials.properties,会直接覆盖对应配置项,所有修改都在IDE项目文件中完成,无需改动系统文件。
方案二:条件化添加Profile专属配置源
如果希望通过代码层面实现自动适配,可修改配置类结合@Profile注解,仅在Develop环境加载高优先级配置:
- 在
src/main/resources下创建application-develop.properties,写入覆盖用的配置项; - 修改你的配置类:
@PropertySources({ @PropertySource("file:${user.home}/.app/credentials.properties"), @PropertySource(value = "classpath:application.properties") }) // 仅当develop profile激活时加载该配置源,order设为1确保后加载(覆盖前面的配置) @Profile("develop") @PropertySource(value = "classpath:application-develop.properties", order = 1) public class AppConfig { // 配置类原有内容 }
order=1会让这个配置源在原有两个配置之后加载,从而覆盖外部文件中的同名配置项,所有修改同样在IDE项目文件内完成。
内容的提问来源于stack exchange,提问作者jnemecz
相关产品推荐
相关产品推荐

