基本语法
- key: value;kv之间有空格
- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用tab,只允许空格
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
- 字符串无需加引号,如果要加,单引号’’、双引号""表示字符串内容会被 转义、不转义
1.对象:键值对的集合。map、hash、set、object
#行内写法:
k: {k1:v1,k2:v2,k3:v3}
或者
k:
k1: v1
k2: v2
k3: v3
2.数组:一组按次序排列的值。array、list、queue
#行内写法:
k: [v1,v2,v3]
#或者
k:
- v1
- v2
- v3
3.实例:
package com.example.springboothello.entity;
import lombok.Data;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Data
public class Person {
private String userName;
private Boolean boss;
private Date birth;
private Integer age;
private Pet pet;
private String[] interests;
private List<String> animal;
private Map<String, Object> score;
private Set<Double> salarys;
private Map<String, List<Pet>> allPets;
}
@ToString
@Data
public class Pet
{
private String name;
private Double weight;
}
新建application.yaml:
person:
userName: 苏七
boss: false
birth: 2019/12/12 20:12:33
age: 18
pet:
{name: tomcat,weight: 55.1}
interests: [篮球,游泳]
animal: [狗,猫]
score:
english:
first: 10
last: 50
chinese: {first: 128,second: 136}
math: [131,140,148]
salarys: [3999,4999.98,5999.99]
allPets:
health: [{name: mario,weight: 47},{name: mario,weight: 47}]
sick: [{name: mario,weight: 47},{name: mario,weight: 47}]
将类与配置文件绑定,类中加上@Component和 @ConfigurationProperties(prefix = "person")
package com.example.springboothello.entity;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Component
@ConfigurationProperties(prefix = "person")
@Data
public class Person {
private String userName;
private Boolean boss;
private Date birth;
private Integer age;
private Pet pet;
private String[] interests;
private List<String> animal;
private Map<String, Object> score;
private Set<Double> salarys;
private Map<String, List<Pet>> allPets;
}
自定义的类和配置文件绑定一般没有提示。若要提示,添加如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
controller:
@RestController
public class HelloController
{
@Autowired
private Person person;
@RequestMapping("/person")
public Person test()
{
return person;
}
}