SpringBoot- 技术专题 -war 包部署读取外部配置 Yml

背景说明
当我们使用 springboot 开发时,有的时候需要打 war 包在外部 tomcat 部署,方便运维人员维护,但是修改配置文件后重新打包给运维的时候,又需要修改一些配置这样还是不方便维护。
springboot 加载 yml 文件时发现需要用到其他的类,YamlPropertiesFactoryBean 和 YamlMapFactoryBean。
配置类实现 EnvironmentPostProcessor 接口
EnvironmentPostProcessor 是 springboot 支持动态读取文件的接口,实现 EnvironmentPostProcessor 接口覆写 postProcessEnvironment 方法
在 postProcessEnvironment 方法实现读取外部配置文件
使用 YamlPropertiesFactoryBean 来读取 yml 配置文件,getObject()方法可以获取 Properties
首先我把 springboot.yml 配置文件放在 tomcat 目录的 conf 目录下(可以根据自己需求修改目录)

实现 EnvironmentPostProcessor 在方法中完成 yml 配置读取
在 resources 目录下建一个 META-INF 文件目录,在目录中建一个 spring.factories 文件,在文件中配置自己实现的动态读取文件类

在 pom.xml 中配置 maven 打包时移除配置文件

最后 tomcat 启动,springboot 启动会加载 datasource 配置创建'sqlSessionFactory',正序正常启动就说明这种方式读取 yml 配置文件没有问题。

正常启动,成功加载到了.yml 配置文件。
最后说一下 logback.xml 配置文件丢到外面直接在.yml 配置文件中配置好路径就可以了

参考文章:
https://blog.csdn.net/uknowzxt/article/details/94613582
https://blog.csdn.net/luckyrocks/article/details/79248016
评论