YAML语法入门
1、基本格式
- 用缩进表示层级,左对齐的数据属于同一层级;
- K:(空格)v 表示一个键值对
- 大小写敏感
- "#"表示注释
server:
port: 8081
spring:
#这是注释
datasource:
url: jdbc:oracle:thin:@localhost:1521:orcl
driver-class-name: oracle.jdbc.driver.OracleDriver
username: ABC
password: ABC
2、数据类型
yml支持以下数据类型
- 对象:键值对的集合,包括:map、字典
- 数组:一组按次序排列的值,包括:list和set
- 纯量(scalars):即字面量,单个的、不可再分的值。包括:数字,字符串,布尔
3、设置方式
3.1、纯量
属性设置:
property:
#字符串一般情况下不需要使用引号
str0: 字符串
#使用双引号时
str1: "特殊转移字符\n被双引\t号包含时"
#使用单引号时
str2: '特殊转移字符\n被单引\t号包\r含时'
num: 3.25 #数字
bool: true #布尔值
date: 2021/03/03 #日期
time: 2021/03/03 17:12:35 # 时间
birth: 2021-03-03 17:12:35
实体类:
@Component
@ConfigurationProperties(prefix = "property")
public class PropertyObject {
private String str0;
private String str1;
private String str2;
private String str3;
private BigDecimal num;
private boolean bool;
private Date date;
private Date time;
@JsonFormat(timezone = "GMT+8",pattern="yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private LocalDateTime birth;
}
输出:
{"str0":"字符串","str1":"特殊转移字符\n被双引\t号包含时","str2":"特殊转移字符\\n被单引\\t号包\\r含时","str3":null,"num":3.25,"bool":true,"date":"2021-03-02T16:00:00.000+00:00","time":"2021-03-03T09:12:35.000+00:00","birth":"2021-03-03 17:12:35"}
3.2、数组、list、set
属性设置:
property:
#数组 多行写法,以 “- 值” 表示一个元素
ints:
- 1
- 2
- 3
- 4
# 数组,单行写法,与正常初始化一个数组一样
strings: [abc,err,ok]
list: [123,654,3.25,euuu]
set:
- abc
- yue
- ok
实体类:
@Component
@ConfigurationProperties(prefix = "property")
public class PropertyObject {
private int[] ints;
private String[] strings;
private List list;
private Set set;
}
输出:
{"ints":[1,2,3,4],"strings":["abc","err","ok"],"list":[123,654,3.25,"euuu"],"set":["abc","yue","ok"]}
3.3、对象、map
属性设置:
property:
#单行写法
map: {abc: abc,sks: 123}
#多行写法
person:
name: 张三
age: 25
people:
- {name: lisi,age: 13}
- {name: 金士顿,age: 24}
实体类:
@Component
@ConfigurationProperties(prefix = "property")
public class PropertyObject {
private Map map;
private Person person;
private List<Person> people;
}
输出:
{"map":{"abc":"abc","sks":123},"person":{"name":"张三","age":25},"people":[{"name":"lisi","age":13},{"name":"金士顿","age":24}]}
3.4、锚点与引用
yml可以通过 & 锚点和 ***** 别名,实现值引用
& 用来建立锚点(defaults),<< 表示合并到当前数据, * 用来引用锚点。
属性设置:
property:
person: &zhangsan
name: 张三
age: 25
person2: &p2
<<: *zhangsan
people:
- {name: lisi,age: 13}
- {name: 金士顿,age: 24}
- <<: *zhangsan
- <<: *p2
实体类:
@Component
@ConfigurationProperties(prefix = "property")
public class PropertyObject {
private Person person;
private Person person2;
private List<Person> people;
}
输出:
{"person":{"name":"张三","age":25,"list":null},"person2":{"name":"张三","age":25,"list":null},"people":[{"name":"lisi","age":13,"list":null},{"name":"金士顿","age":24,"list":null},{"name":"张三","age":25,"list":null},{"name":"张三","age":25,"list":null}]}