yaml 简单使用

    xiaoxiao2023-11-29  185

    什么是 YAML

    YAML 可以视为是 JSON 的一个超集,是一种方便的定义层次配置数据的格式,结构层次上清晰明了,配置简单易读、易用。


    YAML 的基本规则

    大小写敏感使用缩进表示层级关系禁止使用tab缩进,只能使用空格缩进长度没有限制,只要元素对齐就表示这些元素属于一个层级使用#表示注释字符串可以不用引号标注

    YAML 支持的数据结构

    使用 : 表示一个键值对,对齐的缩进表示同一个map,同时也表示一个对象

    # person.name person.age person.weight person.height person: name: ke age: 22 weight: 60.0 height: 170.0 # person : {name : ke,age : 22,weight : 60.0,height : 170.0}

    使用 {} 用 JSON格式也可以达到表达 map 的效果

    person: {name: ke,age: 22,weight: 60.0,height: 170.0}

    使用 - 来表示一个数组

    person: name: ke age: 22 weight: 60.0 height: 170.0 brothers: - Jack - Jim - John

    使用 [ ] 同样可以用来表示一个数组

    person: {name: ke,age: 22,weight: 60.0,height: 170.0,brothers: [Jack,Jim,John]}

    使用 | 来表示文字块

    word: | This is a word

    使用 > 告诉YAML编译器给所有新行加上条纹,并将输入的文本作为一个长行处理


    SpringBoot 中的使用

    在 application.yml 中的 spring.profiles.active 中指定使用环境

    # spring.profiles.active spring: profiles: active: dev

    SpringBoot 会去调用对应的yml文件,调用规则为 application-activeValue.yml (其中activeValue指的是spring.profiles.active 指定的值),例如,active是dev,则去使用的配置文件是 application-dev.yml,如果active是test,则使用的配置文件是 application-test.yml

    指定使用环境 yml 文件,如果有属性和 applicatioin.yml 重复,则使用环境的 yml文件会覆盖 application.yml文件

    #application.yml spring: profiles: active: test test: testString #application-test.yml test: testtesttest # 此时SpringBoot中 test 的值是 testtesttest

    注入一个Bean

    package com.zyy.boot.bean; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @Data @ConfigurationProperties(value = "person") public class Person { private String name; private Integer age; private Double weight; private Double height; private String[] brothers; }

    使用 @Value 获取配置信息

    package com.zyy.boot.controller; import com.zyy.boot.bean.Person; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @Slf4j public class TestController { @Value("${test}") private String testString; @Value("${person.name}") private String name; @Autowired private Person person; @RequestMapping("test") public String test(){ // testtesttest log.info(testString); // ke log.info("{}",name); // person : Person(name=ke, age=22, weight=60.0, height=170.0, brothers=[Jack, Jim, John]) log.info("person : {}",person); return testString; } }
    最新回复(0)