一、等价写法
yaml虽然对格式严格要求,但支持多种写法。
1.1 数组
方式一
list_by_dash:
- foo
- bar
方式二
list_by_square_bracets: [foo, bar]
1.2 map
方式一
map_by_indentation:
foo: bar
bar: baz
方式二
map_by_curly_braces: {foo: bar, bar: baz}
1.3 String
方式一
string_no_quotes: Monty Python
方式二
string_double_quotes: "Monty Python"
方式三
string_single_quotes: 'Monty Python'
二、长字符串
通过大于号后面追加一个长字符串
disclaimer: >
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In nec urna pellentesque, imperdiet urna vitae, hendrerit
odio. Donec porta aliquet laoreet. Sed viverra tempus fringilla.
三、多行字符串
但如果你想写一个带换行的多行字符串,使用 |
mail_signature: |
Martin Thoma
Tel. +49 123 4567
四、变量
email: &emailAddress "info@example.de"
id: *emailAddress
第一行通过& 定义变量,在第二行可以使用 *emailAddress 引用这个变量。
五、类型转换
我们可以定义通用的类型
price: !!float 42
id: !!str 42
还可以定义特点编程语言支持的类型
tuple_example: !!python/tuple
- 1337
- 42
set_example: !!set {1337, 42}
date_example: !!timestamp 2020-12-31
六、单文件拆分成多个
子配置文件名为application-filename.yml
spring:
profiles:
include: filename
多个子文件
spring:
profiles:
include:
- filename1
- filename2
七、多文档支持
YAML支持使用三个破折号分割文档---
,---
上下两部分会作为两个独立的文档同等对待。
foo: bar
---
fizz: buzz
使用场景:我们在k8s 里面经常将deployment和sevice 放到同一个yaml文件中。
八、配置List数组对象并映射
1、User实体类
@Data
public class User {
private Integer id;
private String name;
private Integer age;
}
2、yaml配置
com:
company:
list:
- id: 1
name: tom
age: 20
- id: 12
name: jerry
age: 25
3、UserList配置类
@Configuration
@ConfigurationProperties(prefix = "com.company")
@Data
public class UserList {
private List<User> list;
}
4、测试
@Test
public void listTest(){
List<User> list = userList.getList();
for(User user:list){
System.out.println(user);
}
System.out.println(userList);
}
网友评论