解决SpringBoot读取依赖模块中application.yml配置失效问题
起因
业务中搭建SpringBoot项目抽出一个公共的common模块,其他服务依赖于common。
例如client-service的模块,依赖于common,配置文件分为application.yml、application-dev.yml、application-prod.yml,存放于resource目录下,application.yml为主配置文件,通过spring.profiles.active属性指定其他配置文件,开发时指定为dev环境,线上指定为prod。
common中存在application.yml配置文件,存放于resource目录下,里面是多个模块的通用配置,例如MyBatisPlus中逻辑删除值的指定、是否开启驼峰命名等。
问题
编译后运行发现common中application.yml内MyBatisPlus的相关配置均未生效,所有的增删改查操作均未判断delete_flag
原因
SpringBoot如果自身有application.yml,就会覆盖依赖模块的同名配置文件。由于在client-service模块创建了application.yml,导致common模块的application.yml被覆盖。
解决方法
更改配置文件名
修改common模块的配置文件名称,例如修改为application-common.yml,再将client-service模块的application.yml的spring.profiles.active属性值修改为dev,common,将client-service模块的application-dev.yml和common中application.yml同时引入。由于client-service模块没有application-common.yml,就会去common模块中找,以此达到补充加载的目的。
**缺点:**如果不小心起重名了,就会覆盖整个配置,而不是作为补充配置加载,并且不方便切换环境。
更改配置文件位置
在common模块的resource文件夹下创建config文件夹,并把配置文件移入其中。官方文档也是推荐这种方法:
7.2.3. External Application Properties
Spring Boot will automatically find and load
application.propertiesandapplication.yamlfiles from the following locations when your application starts:
- From the classpath
- The classpath root
- The classpath
/configpackage- From the current directory
- The current directory
- The
config/subdirectory in the current directory- Immediate child directories of the
config/subdirectory
jar目录:./config/
jar包目录:./工程根目录:
./config/工程根目录:
./依赖的其他
jar包或src代码目录:classpath:/config/依赖的其他
jar包或src代码目录:classpath:/加载的优先级顺序是从上向下加载,并且所有的文件都会被加载,高优先级的内容会覆盖底优先级的内容,形成互补配置
若client-service模块和common模块的配置文件同时存在,会优先用client-service模块的配置,common模块的配置会作为补充加载
参考
springboot 读取依赖模块的yml配置 - Visionki
Spring Boot Reference Documentation
Spring Boot 配置文件加载的优先级和指定多个外部配置文件_51CTO博客_springboot配置文件优先级顺序