yaml文件的学习
基本语法
- key: value;kv之间有空格
- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用tab,只允许空格
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
- 字符串无需加引号,如果要加,单引号’’、双引号""表示字符串内容会被 转义、不转义
基本写法
键值对:k v
对象:
#行内写法:
k: {k1:v1,k2:v2,k3:v3}
#或
k:
k1: v1
k2: v2
k3: v3
数组
#行内写法:
k: [v1,v2,v3]
#或者
k:
- v1
- v2
- v3
#注意数组的 - 和value之间也是有空格的
下面是一个例子
@ConfigurationProperties(prefix="person") //綁定配置文件前綴 @Component //注册到spring容器中 @ToString @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; } @Data @NoArgsConstructor @AllArgsConstructor public class Pet { private String name; private double weight; }
yaml文件配置(给实体类赋值的过程)
person:
userName: zhangsan
boss: false
birth: 2019/12/12 20:12:33
age: 18
pet:
name: tomcat
weight: 23.4
interests: [篮球,游泳]
animal:
- jerry
- mario
score:
english:
first: 30
second: 40
third: 50
math: [131,140,148]
chinese: {first: 128,second: 136}
salarys: [3999,4999.98,5999.99]
allPets:
sick:
- {name: tom}
- {name: jerry,weight: 47}
health: [{name: mario,weight: 47}]
测试访问
@RestController public class PeopleController { @Autowired Person person; //person从容器中获取【Person类的@Component注解】 @RequestMapping("/person") private Person person(){ return person; } }
配置文件-自定义类绑定的配置提示
导入依赖,我们即可在编写yaml文件时有相应的提示信息(需要重启项目)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <!-- 下面插件作用是工程打包时,不将spring-boot-configuration-processor打进包内,让其只在编码的时候有用 --> <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>
测试:

浙公网安备 33010602011771号