SpringBoot读取外部配置文件,避免更新jar包内配置文件重新打包部署
如果springBoot项目与配置文件不分离,那么每次修改配置文件都需要重新重新打包部署应用,十分麻烦。解决方法是让springboot读取外部配置文件,实现应用与配置分离。
先看一下官方文档:
24.3 Application property files
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).
SpringApplication可以从四种方式中读取到配置文件,并且是有优先级的,所有方式下的配置文件都会被读取,高优先级的内容会覆盖底优先级的内容。
1.在jar包的同一目录下建一个config文件夹,然后把配置文件放到这个文件夹下
2.直接把配置文件放到jar包的同级目录
3.在classpath下建一个config文件夹,然后把配置文件放进去
4.在classpath下直接放配置文件
我们平常将项目打成jar包之后,配置文件会被放在BOOT-INF的classes目录下,这就是上面所说的第四种方式,也是优先级最低的配置文件读取方式。
那么我们就可以使用第一、第二种方式来实现应用与配置分离,比如:
这样既方便管理配置文件,也实现了修改配置文件不需要重新打包应用
除此之外,还可以通过jar包启动命令指定配置文件,比如:
java -jar *.jar --spring.config.location=config/application.yml