配置文件
Spring Boot 配置文件可以是 .properties 类型或者 .yaml 类型。
# Yaml常用的语法
yaml 通过代码缩进来表示代码块
- 字符串
version: 3.2.0
1
- 对象
admin:
name: admin
age: 23
1
2
3
2
3
- 数组
roleList:
- name: name1
- name: name2
personList:
- name: name1
age: 2
- name: name2
age: 4
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 配置读取
# 1、 通过 @Value 读取
首先在文件application.yml中定义一个配置 version
。
version: 3.2.1
1
然后通过注解 @Value
直接读取配置值。
@Component
class Config {
@Value("${version}")
private String version;
}
1
2
3
4
5
2
3
4
5
# 2、通过 @ConfigurationProperties 读取
先定义一个配置文件,包含对象、数组。
admin:
name: NAME
password: PWD
title:
- titleA
- titleB
1
2
3
4
5
6
2
3
4
5
6
通过 @ConfigurationProperties
注解读取配置将容器中的对象赋值,需要配合 @Component
使用。
@Component
@ConfigurationProperties(prefix = "admin")
public class AdminConfig {
private String name;
private String password;
private List<String> titles;
// getter setter
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
在需要使用的地方直接注入这个对象即可直接访问配置文件中的值。
class Test {
@Autowired
private AdminConfig admin;
}
1
2
3
4
5
2
3
4
5
# 3、使用@PropertySource指定配置文件
使用 @PropertySource 指定配置文件,会从指定文件读取配置而不是 application.yml
@PropertySource("classpath:myconfig.yml")
@Data
public class AdminConfig {
@Value("${version}")
private String version;
}
1
2
3
4
5
6
2
3
4
5
6
# 多配置文件
SpringBoot应用在开发、测试、生产环境需要不同的配置文件。可以通过 application-{}.yml
定义多个配置文件,然后在主配置文件中指定使用的配置文件。
# 1、定义多个配置文件
application.yml
、application-dev.yml
、application-test.yml
、application-prod.yml
# 2、在主配置文件中指定开发环境
# application.yml:
spring:
profiles:
active: dev
1
2
3
4
2
3
4