Spring Boot 自定义配置文件位置
Spring Boot 启动项目时,可以通过如下两个配置来指定配置文件:
spring.config.location
spring.config.additional-location
这两个配置都可以使用命令行参数或 JVM 属性来设置:
1 | java -Dspring.config.location=E:\Documents\config\application-local.properties cn.z2huo.demo.spring.pkg.SpringPackageApp |
如果你不显式指定 spring.config.location
,Spring Boot 会按照以下优先级顺序(从高到低)自动在以下位置查找 application.properties
或 application.yml
文件:
file:./config/
,当前目录下的config
文件夹file:./
,当前目录classpath:/config/
,类路径下的config
文件夹classpath:/
,类路径根目录
高优先级的配置会覆盖低优先级的配置。
另外,这两个配置,可以指定文件,也可以指定目录。如果存在多个位置,需要使用逗号分隔多个配置。
通过 spring.config.location
指定位置的配置具有最高的优先级,会覆盖默认位置的配置和 spring.config.additional-location
指定位置的配置。也就是说,使用了 spring.config.location
指定配置文件之后,会忽略源项目中类路径下的配置文件,比如 resources/application.properties
。
如果指定的配置文件可能不存在,又希望应用不要因此启动失败,可以在路径前加上 optional:
,示例如下:
1 | java -Dspring.config.location=optional:E:\Documents\config\application-local.properties -jar myJar.jar |
location
和 additional-location
的区别
代码
location
会替换默认配置源,而 additional-location
是追加额外配置源。前者会导致原有配置失效,后者与原配置形成互补。
例如有下面的程序:
1 |
|
1 |
|
项目的 resources
目录下有两个配置文件,分别是 application.properties
和 application-local.properties
,内容如下:
1 | spring.application.name=spring-package-demo |
1 | test.property.a=a |
另外,在项目外部还有一个单独的配置文件 application-other.properties
,内容如下:
1 | test.property.a=aaa |
现象
使用 spring.config.location
使用 --spring.config.location=E:\Documents\config\application-other.properties
,输出结果如下:
1 | property a is aaa, property b is bbb, property c is ccc, property d is this is d default |
可以看到 resources/application.properties
文件中的 spring.application.name
配置输出为空。
resources/application-local.properties
文件中的 test.property.d
属性没有输出 d
。并且,a
、b
、c
三个属性都为 application-other.properties
中的配置,验证了:
通过
spring.config.location
指定位置的配置具有最高的优先级,会覆盖默认位置的配置和spring.config.additional-location
指定位置的配置。
使用 spring.config.additional-location
使用 --spring.config.additional-location=E:\Documents\config\application-other.properties
,输出结果如下:
1 | property a is aaa, property b is bbb, property c is ccc, property d is d |
可以看到,a
、b
、c
三个属性输出的值都为 application-other.properties
文件中的值,application-other.properties
中不存在的 d
没有被覆盖掉,另外 spring.application.name
也正常输出了。
表示 spring.config.additional-location
是覆盖原有属性和补充属性,并不是对配置文件的完全替换。
相关链接
OB links
OB tags
#SpringBoot