1. 简介
- YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)。
- 非常适合用来做以数据为中心的配置文件。
2. 基本语法
- key: value (冒号之后有一个空格)
- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用tab,只允许空格(IDEA中无所谓,自动将tab转化为4个空格,可以放心使用)
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
- 字符串无需加引号,如果要加,单引号’'表示转义字符不生效,双引号""表示转义字符生效
3. 数据类型
-
字面量:单个的、不可再分的值。可以是date、boolean、string、number、null
k: v
-
对象:键值对的集合。可以是map、hash、object
# 行内写法: k: {k1: v1, k2: v2, k3: v3} # 或 k: k1: v1 k2: v2 k3: v3
-
数组:一组按次序排列的值。可以是array、list、set、queue
#行内写法: k: [v1, v2, v3] #或者 k: - v1 - v2 - v3
经过测试,yaml中的key不能为中文,而value可以。
4. 示例
Java中的Component和Controller
@ConfigurationProperties(prefix = "people")
@Component
@Data
public class People {
private Integer id;
private String name;
private Boolean isMan;
private Date birth;
private String[] interests;
private List<String> childrenNames;
private Set<String> cars;
private Map<String,Object> scores;
private Map<String,List<Pet>> allPets;
}
@Data
class Pet {
private String name;
private Double weight;
}
@RestController
public class TestController {
@Autowired
People people;
@RequestMapping("/people")
public People getPeople(){
return people;
}
}
YAML配置文件
people:
id: 1
name: 张三
isMan: true
birth: 2000/01/01
interests: [篮球,足球]
childrenNames:
- 张大娃
- 张二娃
cars:
- 奔驰
- 宝马
scores:
math: 148
yuwen: 120
allPets:
dogs:
- name: 大狗
weight: 20.1
- name: 二狗
weight: 18.66
cats: [{name: 大猫,weight: 6.1},{name: 二猫,weight: 5.1}]
{"id":1,"name":"张三","isMan":true,"birth":"1999-12-31T16:00:00.000+00:00","interests":["篮球","足球"],"childrenNames":["张大娃","张二娃"],"cars":["奔驰","宝马"],"scores":{"math":148,"yuwen":120},"allPets":{"dogs":[{"name":"大狗","weight":20.1},{"name":"二狗","weight":18.66}],"cats":[{"name":"大猫","weight":6.1},{"name":"二猫","weight":5.1}]}}
5. 自定义类绑定的配置提示
- 自定义的类和配置文件绑定一般没有提示。若要提示,添加如下依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
- 在打包的时候,可以把这个包排除,因为这个包只是为了在开发的时候能够有提示作用,对打包的结果没有影响
<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>
6. 解决视图乱码问题
在application.yaml中填写中文字符,在读取该文件时会出现中文乱码问题。一般是IDEA中没有设置的问题。
解决方式:
IDEA环境,首先File->settings->Code style->File Encoding
将project encoding和Default encoding for properties files都设置为UTF-8,在Transparent native-to ascii conversion左侧勾上。
再重新运行项目即可在网页中正常显示中文字符。(需要注意键值对的键不能使用中文,否则会出错)