目录YAML 是 “YAML Ain’t a Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件等.
YAML 的配置文件后缀为 .yml 或 .yaml ,如:application.yml 或 application.yaml。比起 XML 更轻量级。
- 五、配置文件 YAML
- 5.1. 配置文件 yaml 的用法
- 5.1.1. 基本语法
- 5.1.2. 数据类型
- 5.1.2.1. 字面量
- 5.1.2.2. 对象
- 5.1.2.3. 数组
- 5.1.3. 示例
- key: value:key 和 value 之间有一个空格
- 大小写敏感
- 使用缩进表示层级关系,不允许使用 tab,只允许空格
- 不明确指定空格个数,相同层级的只需要左对齐即可
- # 表示注释,单行注释
- 字符串不需要加引号
- '':单引号 会进行转义
- "":双引号 不会进行转义
单个的,不可分割的值,如:date、number、boolean、string、null 等。
key: value5.1.2.2. 对象
键值对的集合,如:map 等。
行内写法
key: {key1:value1, key2:value2, ...}
多行写法
key:
key1: value1
key2: value2
key3: vaule3
...
5.1.2.3. 数组
一组按次序排列的值,如:array、list 等。
行内写法
key: [vaule1, value2, value3, ...]
多行写法
key:
- value1
- value2
- value3
...
5.1.3. 示例
YamlTest.java
@Data
@Component
@ConfigurationProperties(prefix = "yaml-test")
public class YamlTest {...}
YamlController.java
package cn.com.springboot.demo.controller;
import cn.com.springboot.demo.bean.YamlTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class YamlController {
@Autowired
private YamlTest yamlTest;
@RequestMapping("/yaml")
public YamlTest yaml() {
return yamlTest;
}
}
字符串
# 字符串,不需要加引号(单双都不需要) # yaml-test.name: 张三 # 或 yaml-test: name: 张三
转换为 json 为:
{"name":"张三"}
- 当字符串中包含空格时,需要使用双引号包起来
- 多行字符串:
str1:
abc
def
转换为 json 为:
{"str1":"abc def"}
- 换行符会转换为空格
- 字符串使用 | :
str1: |
abc
def
转换为 json 为:
{"str1":"abcndef"}
- 换行符会被保留
- 字符串使用 > :
str1: >
abc
def
# 上边有空行
转换为 json 为:
{"str1":"abc defn"}
- 折叠换行
单引号
yaml-test: # 单引号 name1: '张三n李四'
转换为 json 为:
{"name1":"张三\n李四"}
- 单引号中还有单引号的话,需要再加一个‘(单引号)进行转义
双引号
yaml-test: # 单引号 name1: '张三n李四'
转换为 json 为:
{"name1":"张三n李四"}
布尔类型
yaml-test: # 布尔类型,直接写 true 或 false bool: true
转换为 json 为:
{"bool":true}
整数
yaml-test: # 整数类型 age: 18
转换为 json 为:
{"age":18}
浮点数
yaml-test: # 整数类型 float-number: 12.3
转换为 json 为:
{"floatNumber":12.3}
空值
yaml-test: # 空值,使用 ~ 或 null 表示 # object: null object: ~
转换为 json 为:
{"object":""}
日期
yaml-test: # 日期,格式:yyyy/MM/dd # 使用 yyyy-MM-dd 会报错 # failed to convert java.lang.String to java.util.Date (caused by java.lang.IllegalArgumentException) date: 2021/10/06
转换为 json 为:
{"date":"2021-10-05T16:00:00.000+00:00"}
对象(map等)
yaml-test:
# User 对象
# 行内写法
# user: {name: 张三, age: 27}
# 多行写法
user:
name: 张三
age: 27
转换为 json 为:
{"user":{"name":"张三","age":"27"}}
数组(集合等)
yaml-test:
# 数组
# 行内写法
# arrs: [a, b, c]
# 多行写法
arrs:
- a
- b
- c
转换为 json 为:
{"arrs":["a","b","c"]}
引用
yaml-test:
# 引用
defaults: &default
name: 李四
user1:
<<: *default
age: 27
转换为 json 为:
{"user1":{"name":"李四","age":"27"}}
- &:建立锚点
- <<:合并到当前数据
- *:引用锚点
另外一个示例:
yaml-test:
# 引用
defaults: &default a1
arrs1:
- *default
- b
- c
转换为 json 为:
{"arrs1":["a1","b","c"]}
强制类型转换
yaml-test: # !! 表示强制类型转换 age1: !!int "123"
转换为 json 为:
{"age1":123}



