SpringBoot-yaml配置

Yaml

维基百科:

YAML是”YAML Ain’t a Markup Language”(YAML不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:”Yet Another Markup Language”(仍是一种标记语言)[3],但为了强调这种语言以数据做为中心,而不是以标记语言为重点,而用反向缩略语重命名。

基本语法

  • 冒号后面有一个空格
  • 对空格要求严格
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 对象
student:
name: yiqing
age: 25

# 行内元素
student: {name: John Smith, age: 33}
- name: Mary Smith
age: 27

# 数组
men: [John Smith, Bill Jones]
women:
- Mary Smith
- Susan Williams

SpringBoot中使用yaml

在springboot中,yaml可以注入实体类中

使用@ConfigurationProperties注解

  • 将配置文件的属性值,映射到这个组件中,参数prefix是将配置文件中的person下面的所有属性一一对应

  • 只有是容器中的组件,才可以使用这个注解

示例:

  1. 建实体类(使用了lombok)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    @Component
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @ConfigurationProperties(prefix = "person")
    public class Person {
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
    }

    @Component
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class Dog {
    private String name;
    private Integer age;
    }

  2. resources新建application.yaml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    person:
    name: yiqing
    age: 3
    happy: false
    birth: 2020/11/20
    maps: {k1: v1,k2: v2}
    lists:
    - code
    - music
    - girl
    dog:
    name: 旺财
    age: 3
  3. 测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @SpringBootTest
    class Springboot02ConfigApplicationTests {

    @Autowired
    private Person person;
    @Test
    void contextLoads() {
    System.out.println(person);
    }

    }
  4. 也可以使用EL表达式

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    person:
    name: yiqing${random.uuid}
    age: ${random.int}
    happy: false
    birth: 2020/11/20
    maps: {k1: v1,k2: v2}
    lists:
    - code
    - music
    - girl
    dog:
    name: ${person.hello:hello}
    age: 3

总结

  • yaml和properties都可以取值,但是推荐yaml
  • 如果在业务中,只需要获取配置文件中的某个值,直接@Value
  • 如果专门编写了一个JavaBean来和配置文件进行映射,就直接使用ConfigurationProperties