起因
业务中搭建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.properties
andapplication.yaml
files from the following locations when your application starts:
From the classpath
The classpath root The classpath /config
packageFrom the current directory
The current directory The config/
subdirectory in the current directoryImmediate 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[1]
Spring Boot Reference Documentation[2]
Spring Boot 配置文件加载的优先级和指定多个外部配置文件_51CTO博客_springboot配置文件优先级顺序[3]
参考资料
springboot 读取依赖模块的yml配置 – Visionki: https://blog.visionki.com/index.php/archives/82/
[2]
Spring Boot Reference Documentation: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.external-config.files
[3]
Spring Boot 配置文件加载的优先级和指定多个外部配置文件_51CTO博客_springboot配置文件优先级顺序: https://blog.51cto.com/u_1472521/4996341
原文始发于微信公众号(程序员段宝):解决SpringBoot读取依赖模块中application.yml配置失效问题
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/235087.html