目录
1、文件类型
1.1、properties
1.2、yaml
1.2.1、简介
1.2.2、基本语法
1.2.3、数据类型
2、配置提示
同以前的properties用法
YAML 是 "YAML Ain't Markup Language"(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。
非常适合用来做以数据为中心的配置文件
k: v
行内写法: k: {k1:v1,k2:v2,k3:v3}
#或
k:
k1: v1
k2: v2
k3: v3
行内写法: k: [v1,v2,v3]
#或者
k:
- v1
- v2
- v3
引入依赖lombok
org.projectlombok
lombok
在项目中新建实体类 cn.xs.boot.bean.Pet
import lombok.Data;
import lombok.ToString;@ToString
@Data
public class Pet {
/* 名字 */
private String name;
/* 体重 */
private Double weight;
}
在项目中新建实体类 cn.xs.boot.bean.Person
import lombok.Data;
import lombok.ToString;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
/
@ToString
@Data
public class Person {
/* 姓名 */
private String userName;
/* 是否为老板 */
private Boolean boss;
/* 生日 */
private Date birth;
/* 年龄 */
private Integer age;
/* 宠物 */
private Pet pet;
/* 兴趣 */
private String[] interests;
/* 动物 */
private List animal;
/* 分数 */
private Map score;
/* 薪资 */
private Set salary;
/* 所有的宠物 */
private Map> allPets;
}
创建 application.yml 文件,YAML 文件的后缀可以是 .yaml 也可以是 .yml
将 Person 放入容器中,指定要绑定的配置文件
@ConfigurationProperties(prefix = "person")
@Component
@ToString
@Data
public class Person {}
在配置文件中配置 Person
person:
userName: hereshui
boss: true
birth: 2021/6/11
age: 18
# interests: [羽毛球,钢琴]
interests:
- 羽毛球
- 钢琴
animal: [阿猫,阿狗]
# score: {mathematics: 100,physics: 98,chemistry: 98}
score:
mathematics: 100
physics: 98
chemistry: 98
salary:
- 1.25
- 0.5
pet:
name: 塞班
weight: 99.99
allPets:
sick:
- {name: 阿狗,weight: 99.99}
- name: 阿猫
weight: 88.88
- name: 阿鼠
weight: 77.77
health: [{name: 阿鸭,weight: 66.66},{name: 阿鸡,weight: 55.55}]
注意调节格式,此处因为粘贴格式错误,运行会导致代码报错。
编写 cn.xs.boot.controller.HelloController 来进行测试
import cn.baisee.boot.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {
/* 注入 Person 对象 */
@Autowired
private Person person;
/**
* 返回容器中的 Person 对象
*
* @return
*/
@RequestMapping("/person")
public Person person() {
return person;
}
}
当 application.yml 与 application.properties 中有相同配置时,以 properties 中的配置为准, properties 的优先级要高于 yaml
自定义的类和配置文件绑定一般没有提示。
org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-maven-plugin org.springframework.boot spring-boot-configuration-processor