介绍
配置文件时用来解决硬编码问题,把可能会发生改变的信息放在一个集中的地方也就说配置文件上,当我们启动某个程序的时候,应用程序会从配置文件中读取数据,并加载运行。
硬编码是指将数据直接嵌入到源代码中,也就说"代码写死",例如手机的字体大小,如果我们采用硬编码的形式,那字体大小就不好更改,如果使用配hi文件,用户通过设置修改字体大小,这份数据就会保存到配置文件上,这样下次启动的时候,手机就可以从配置文件得知字体的大小,就不需要用户进行二次修改了。
配置文件的格式
SpringBoot 配置文件有三种形式:
application.properties
application.yml
application.yaml
其中 .yml 是 .yaml 的简写
在Spring 中默认配置文件为 application.properties
.properties 和 .yml 可以共存在一个项目中,当 .properties 和 .yml 并存时,两个配置文件都会被加载,如果文件内容存在冲突,以.properties 为主,也就说 .properties 优先级更高
但是在实际开发中,我们通常使用一种统一的配置文件格式,以便更好的维护项目
.properties
.properties 的书写格式为 key 和 value 之间使用等号来分割
java
spring.application.name=spring-ioc-demo
my.key=10
my.key2=20
my.key3=30
一般来说单词与单词之间使用 .(英文的点号) 来分割
.yml
key 和 value 使用 : 来分割,并且 key 与 key 之间使用树形结构
java
my:
key1: 10
key2: 20
key3: 30
空格是不可以省略的,不同的级别需要用空格隔开距离,例如上面的 key1、key2 就是和 my 不用级别的,而 key1 和 key2 就是同一级别的,key1: 后面如果要跟上 value 的话,需要使用 空格 来分割。
配置基本数据类型
java
# 字符串
string:
key: Hello
# 布尔类型
boolean:
value1: true
value2: false
# 数字
number:
int:
key1: 10
key2: -45
float:
key: 3.14
# null
test:
key: ~
# 空字符串
empty:
key:
key1: ''
key2: ""
这里要注意 null 的书写为 ~
空字符串的书写可以什么都不写,为了可阅读性,可以加上引号
读取配置文件
@Value
@Value 传递的参数格式为 "${名称}"
@Value 只能获取基本类型或者包装类型的配置数据,如果想要获取配置文件中的对象的数据需要使用 @ConfigurationProperties
java
my:
key1: 10
key2: 20
key3: 30
java
@Configuration
public class YMLDemo {
@Value("${my.key1}")
private Integer key1;
@Value("${my.key2}")
private Integer key2;
@PostConstruct
public void init() {
System.out.println("key1 " + key1);
System.out.println("key2 " + key2);
}
}

@PostConstruct 这个注解的方法会在对象初始化的过程中就执行,所以你会在 spring 项目启动前看到结果
@ConfigurationProperties
@ConfigurationProperties 需要的参数格式为 prefix = "名称" 或者 直接传入 "名称"
@ConfigurationProperties 用来获取对象、集合、Map 等类型的配置信息
java
userinfo:
id: 1
name: zhangsan
age: 20
java
@ConfigurationProperties(prefix = "userinfo")
@Component
@Data
public class User {
private Integer id;
private String name;
private Integer age;
}
java
@Configuration
public class YMLDemo {
@Value("${my.key1}")
private Integer key1;
@Value("${my.key2}")
private Integer key2;
@Autowired
private User user;
@PostConstruct
public void init() {
System.out.println("key1 " + key1);
System.out.println("key2 " + key2);
System.out.println("user: " + user);
}
}

配置集合
List 数据类型的每一个元素前面要加上 - 和 空格来进行分割
List 和 Map 的 yml 的书写格式如下:
java
test:
demo:
- Hello World
- DataStructure
- mysql
- spring
map:
key1: 1
key2: 2
key3: 3
java
@ConfigurationProperties("test")
@Component
@Data
public class Student {
private List<String> demo;
private Map<String, Integer> map;
}
java
@Configuration
public class YMLDemo {
@Autowired
private Student student;
@PostConstruct
public void init() {
System.out.println("student " + student.getDemo());
System.out.println("map " + student.getMap());
}
}

小结
properties 配置是以 key=value 的形式配置的,如下图所示:
从上述配置key看出,properties 配置文件中会有很多的冗余的信息,比如这些:
这时候我们可以使用 yml 来存储配置信息:
在存在复杂的冗余信息的时候,我们可以考虑使用 yml 来保存配置信息,相反我们可以使用 properties