SpringBoot--->yaml原理初探

1、语法

1、空格不能省略

2、以缩进来控制层级关系,只要是左边对齐的一列数据都是同一个层级的。

3、属性和值的大小写都是十分敏感的。

#对象
persion:
name: xian
age: 19
#map
maps: {k1: v1,k2: v2}
#list对象注入
lists:
- code
- monry
- gril
list: [l1,l2,l3]
#注入对象
dog:
name: wangwang
age: 2

2、在对应的类上进行操作

person类注册spring组件

配置文件配置的类名

//注册为spring组件
@Component
// 在配置文件中匹配对应内容
@ConfigurationProperties(prefix = "persion")
public class Persion {
    String name;
    int age;
    Map<Object,Object> maps;
    List<Object> lists;
    Dog dog;

3、测试类自动注入

class HellowouldApplicationTests {
    @Autowired
    Persion persion;
    @Test
    void contextLoads() {
        System.out.println(persion);
    }

}

4、使用时遇到的问题

@ConfigurationProperties(prefix = "persion")    需要匹配对应的名字

报错是需要导的包

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

使用占位符

person:
    name: qinjiang${random.uuid} # 随机uuid
    age: ${random.int}  # 随机int
    happy: false
    birth: 2000/01/01
    maps: {k1: v1,k2: v2}
    lists:
      - code
      - girl
      - music
    dog:
      name: ${person.hello:other}_旺财
      age: 1

@PropertySource :加载指定的配置文件;

@configurationProperties:默认从全局配置文件中获取值;

原文地址:https://www.cnblogs.com/springxian/p/14382283.html