配置文件深入
# 650.配置文件深入
讲讲更多关于配置文件的知识
# 外部配置源
SpringBoot文档中,有专门一节讲配置文件的:
4.2. Externalized Configuration
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允许使用配置文件,这样就可以让一套代码运行在不同的环境
- 可以使用.properties,.yaml,环境变量 和 命令行的方式来指定配置
- 配置文件的值可以通过
@Value
注解直接注入bean中,也可以使用@ConfigurationProperties
将一系列配置绑定到对象中
例如,我们之前安装Java和Maven的时候,都设置过环境变量。我们可以在代码中取出Maven的环境变量:
@RestController
public class HelloController {
@Value("${MAVEN_HOME}")
private String mvn;
@GetMapping("/mvn")
public String getMvn() {
return mvn;
}
}
2
3
4
5
6
7
8
9
10
11
效果:
还可以遍历所有的环境变量,以及一些系统信息(例如Windows版本等):
@SpringBootApplication
public class LearnSpringBootProfileApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(LearnSpringBootProfileApplication.class, args);
ConfigurableEnvironment environment = run.getEnvironment();
Map<String, Object> systemEnvironment = environment.getSystemEnvironment();
Map<String, Object> systemProperties = environment.getSystemProperties();
System.out.println(systemEnvironment);
System.out.println(systemProperties);
}
}
2
3
4
5
6
7
8
9
10
11
12
13
运行结果:
# 配置的优先级
Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:
- Devtools global settings properties in the $HOME/.config/spring-boot directory when devtools is active.
- @TestPropertySource annotations on your tests.
- properties attribute on your tests. Available on @SpringBootTest and the test annotations for testing a particular slice of your application.
- Command line arguments.
- .....
大意:SpringBoot对于加载配置有指定的顺序,并且允许覆盖,越下方的优先级越高(文档中列了17个,这里不全部举出),也不用全部记住,只需记得后面的配置会覆盖前面的配置即可
关于配置文件application.yaml,也是有加载顺序的:
- classpath 根路径(也就是resources目录下)
- classpath 根路径下config目录
- jar包当前目录下
- jar包当前目录的config目录
- /config子目录的直接子目录
也就是从上往下,逐个加载这些配置文件(如果没有则不加载)
例如,在resources目录下新建config目录,然后新建application.yaml:
spring:
profiles:
active: test
2
3
运行结果:test配置文件被加载
我们总结下加载文件的顺序:
首先加载application.yaml文件,根据如下路径加载
- classpath 根路径(也就是resources目录下)
- classpath 根路径下config目录
- jar包当前目录下
- jar包当前目录的config目录
- /config子目录的直接子目录
然后加载指定的Profile
由于后面加载的配置,会覆盖前面加载的配置,因此可以认为后面的配置优先级较高。
已将本文源码上传到 Gitee (opens new window) 和 GitHub (opens new window) 的分支demo2,读者可以通过切换分支来查看本文的示例代码