在开发Spring Boot
应用的时候,也会遇到使用外部配置资源,这些配置资源能够与代码相互配合,避免硬编码 方式,提供应用数据或行为变化的灵活性。也就是说我们需要灵活的用好配置文件,接下来就来介绍获取配置文件的内容的各种姿势。
演示环境
- IntelliJ IDEA 2018.2.1 (Community Edition)
- Spring Boot 2.1.1.RELEASE
- Maven 3.3.9
外部配置资源介绍
1、常见的外部配置资源
在开发的过程中,也许会用到不同的配置资源,这里简单的列一下常见的:
- Properties 文件
- YAML 文件
- XML 文件
- 环境变量
- Java 系统属性
- 命令行参数配置
2、资源的加载顺序
Spring Boot
规定了这些外部配置资源的加载的优先级,详情参考官方文档Externalized Configuration小节。这里简要说明一下:
- 热加载,也就是根目录下的开发工具全局设置属性(当开发工具激活时为
~/.spring-boot-devtools.properties
)。 - 测试配置,具体指
@TestPropertySource
注解和@SpringBootTest#properties
注解属性值。 - 命令行参数。
- Servlet 参数
ServletConfig
和ServletContext
。 java:comp/env
的JNDI
属性。- 先系统属性
System.getProperties()
,再操作系统环境变量。 application-{profile}.properties
(先jar
外后jar
内)。application.properties
(先jar
外后jar
内)。@PropertySource
引入的配置源。- 通过
SpringApplication.setDefaultProperties
方法设置的属性。
这里的加载的优先级,高优先级属性源里设置的属性都会覆盖低优先级的相同属性的值。
读取配置
首先准备一个Spring Boot
项目,这个就不多说了,接下来就开始演示加载配置的不同方式。
1、从application.properties
中加载单个配置
首先我们先编写application.properties
配置文件的部分配置:
properties.id = 1
properties.age = 18
properties.student = true
properties.birth = 2018/12/11
properties.array = a,b,c
properties.list = one,two,three
接下来我们编写一个Controller
,使用@Value
注解和Environment
方式来加载我们获取的配置文件的值,并配置一个/properties
路径验证其正确性。详见PropertiesController
代码:
/**
* 加载properties文件中的属性的 {@link RestController}
*
* @author Jerome Zhu
*/
@RestController
public class PropertiesController implements EnvironmentAware{
@Value("${properties.id}")
private Integer id;
@Value("${properties.name:jerome}")
private String name;
private Integer age;
@Value("${properties.student}")
private Boolean student;
@Value("${properties.birth}")
private Date birth;
@Value("${properties.array}")
private String[] array;
@Value("${properties.list}")
private List<String> list;
@GetMapping("/properties")
public Map<String, Object> getProperties() {
Map<String, Object> result = new LinkedHashMap<>