本文主要集中测试和探讨一下 SpringBoot 的配置文件加载机制。java
一个简单的SpringBoot工程,工程目录结构以下:spring
实现功能:springboot
经过访问 "/person" 这个接口,返回 PersonConfig 配置对象中的name和age属性。bash
resource目录下的 yml 文件配置以下:app
先将其打成 jar 包执行。maven
这里要说一下给Springboot工程打jar包的方法。spring-boot
只须要简单地,在pom文件中的build属性添加下面的配置项便可,无需本身再添加 shade 或者 assembly 指定 mainClass 打包(关于这个实现机制,在后面的文章会集中探讨。)。测试
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.4.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
复制代码
执行命令,运行该 jar 包。ui
java -jar springboot-test-1.0-SNAPSHOT.jar
复制代码
调用接口,查看返回结果。spa
可是在生产环境中,咱们每每须要的是实现可配置。这时候咱们可使用 springboot 提供的一个叫 Externalized Configuration 机制。
参考 springboot 官方文档相关说明以下:
Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to externalize configuration. Property values can be injected directly into your beans by using the @Value annotation, accessed through Spring’s Environment abstraction, or be bound to structured objects through @ConfigurationProperties.
这段话主要提到了 springboot 的四种配置机制:property 文件,yml 文件,环境变量,命令行。其实细看后面的说明,文档中提到了 17 种配置方式,可是鉴于经常使用的的方式主要有这四种,因此如下就这四种机制进行探讨。
咱们在jar包同级目录下放置 yml 配置文件,配置项以下所示:
经过命令行参数指定yml文件路径,执行以下所示的命令:
java -jar springboot-test-1.0-SNAPSHOT.jar
--spring.config.location=file:./application.yml
复制代码
运行结果:
若是此时不在命令行参数中指定结果会怎样,程序会加载jar外的配置文件仍是jar包内部的?
执行下面的指令:
java -jar springboot-test-1.0-SNAPSHOT.jar
复制代码
运行结果:
能够看出来,结果与上面相同,即springboot会优先加载jar包外的 yml 文件,并提取其中参数配置项的值覆盖 jar包内的 yml 文件。
若是咱们把jar外的yml文件删除,会怎样?
可是,若是用命令行指定配置文件的路径,那么全部的配置文件路径均可以么?对此 springboot 是有规范的。
下面咱们把 yml 文件放到一个叫 other 的文件夹下,并经过命令行参数指定文件路径运行。
java -jar springboot-test-1.0-SNAPSHOT.jar
--spring.config.location=file:./other/application.yml
复制代码
此时的运行结果:
并且这些路径之间的优先级以下:
1.file:./config/
2.file:./
3.classpath:/config/
4.classpath:/
复制代码
springboot 扫描配置文件的顺序从1到4。只要扫描到了配置文件,则再也不继续扫描。
如今咱们在 config 目录下和 jar 包同级根目录下同时放置 yml 配置文件。
java -jar springboot-test-1.0-SNAPSHOT.jar
复制代码
运行结果: