SpringBoot 从入门到光头 —— 第四章 配置文件
1. 文件类型
1.1. properties
和以往的 properties
文件用法基本一致
1.2. yaml
1.2.1. 简介
YAML 是 YAML Ain’t Markup Language(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是 Yet Another Markup Language(仍是一种标记语言)。
这种语言非常适合用来做以数据为中心的配置文件
1.2.2. 基本语法
key: value;
键与值之间要有空格- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用
Tab
,只允许使用空格 - 缩进的空格数不重要,只要相同层级的元素左对齐即可(建议一个层级缩进 4 个空格)
#
表示注释- 字符串无需加引号,如果要加,**
‘’
** 与“”
表示字符串内容会被转译/不转译
1.2.3. 数据类型
字面量:单个的、不可再分的值。例如
date
、boolean
、string
、number
、null
k: y
对象:键值对的集合。例如
map
、hash
、set
、object
k: {k1:v1,k2:v2,k3:v3} #或者 k: k1: v1 k2: v2 k3: v3
数组:一组按次序排列的值。例如
array
、list
、queue
k: [v1,v2,v3] #或者 k: - v1 - v2 - v3
1.2.4. 使用示例
application.yaml
# Single quotes will output \n as strings
# Double quotes will output \n as a newline
person:
username: XiaoMing
boss: true
birth: 2021/10/26
age: 18
interests:
- Basketball
- Football
animal:
- cat
- dog
score: {English: 80,Math: 90}
salarys:
- 99999.98
- 99999.99
pet:
name: Dog
weight: 99.99
allPets:
sick:
- {name: Dog,weight: 99.99}
- name: Cat
weight: 88.88
- name: Bug
weight: 77.77
health:
- {name: Flower,weight: 199.99}
- {name: Ming,weight: 299.99}
com.yourname.boot.bean.Person
/**
* @author gregPerlinLi
* @since 2021-10-26
*/
@ConfigurationProperties(prefix = "person")
@Component
@Data
@ToString
public class Person {
private String username;
private Boolean boss;
private Date birth;
private Integer age;
private Pet pet;
private String[] interests;
private List<String> animal;
private Map<String, Object> score;
private Set<Double> salaries;
private Map<String, List<Pet>> allPets;
}
com.yourname.boot.bean.Pet
/**
* @author gregPerlinLi
* @since 2021-10-26
*/
@Data
@ToString
public class Pet {
private String name;
private Double weight;
}
com.yourname.boot.controller.HelloController
/**
* @author gregPerlinLi
* @since 2021-10-26
*/
@RestController
public class HelloController {
@Autowired
Person person;
@RequestMapping(value = "/person")
public Person person() {
return person;
}
}
注意⚠️:当 properties
和 yaml
配置文件同时存在的时候,优先度 properties
> yaml
2. 配置提示
自定义的类和配置文件绑定一般没有提示,如果想要提示的话需要进行导包
pom.xml
<dependencied>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencied>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>