解决SpringBoot读取依赖模块中application.yml配置失效问题

起因

业务中搭建SpringBoot项目抽出一个公共的common模块,其他服务依赖于common

例如client-service的模块,依赖于common,配置文件分为application.ymlapplication-dev.ymlapplication-prod.yml,存放于resource目录下,application.yml为主配置文件,通过spring.profiles.active属性指定其他配置文件,开发时指定为dev环境,线上指定为prod

common中存在application.yml配置文件,存放于resource目录下,里面是多个模块的通用配置,例如MyBatisPlus中逻辑删除值的指定、是否开启驼峰命名等。

问题

编译后运行发现commonapplication.ymlMyBatisPlus的相关配置均未生效,所有的增删改查操作均未判断delete_flag

原因

SpringBoot如果自身有application.yml,就会覆盖依赖模块的同名配置文件。由于在client-service模块创建了application.yml,导致common模块的application.yml被覆盖。

解决方法

更改配置文件名

修改common模块的配置文件名称,例如修改为application-common.yml,再将client-service模块的application.ymlspring.profiles.active属性值修改为dev,common,将client-service模块的application-dev.ymlcommonapplication.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 and application.yaml files from the following locations when your application starts:

  1. From the classpath
    1. The classpath root
    2. The classpath /config package
  2. From the current directory
    1. The current directory
    2. The config/ subdirectory in the current directory
    3. 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[1]

Spring Boot Reference Documentation[2]

Spring Boot 配置文件加载的优先级和指定多个外部配置文件_51CTO博客_springboot配置文件优先级顺序[3]

参考资料

[1]

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

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!