字面量:单个的、不可再分的值。可以是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可以。
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}]}}
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
<optional>trueoptional>
dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-maven-pluginartifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-configuration-processorartifactId>
exclude>
excludes>
configuration>
plugin>
plugins>
build>
在application.yaml中填写中文字符,在读取该文件时会出现中文乱码问题。一般是IDEA中没有设置的问题。
解决方式:
IDEA环境,首先File->settings->Code style->File Encoding
将project encoding和Default encoding for properties files都设置为UTF-8,在Transparent native-to ascii conversion左侧勾上。
再重新运行项目即可在网页中正常显示中文字符。(需要注意键值对的键不能使用中文,否则会出错)