SpringBoot:配置文件yaml

yaml

基本语法:

  • key: value;kv之间有空格
  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进不允许使用tab,只允许空格
  • 缩进的空格数不重要,只要相同层级的元素左对齐即可
  • '#'表示注释
  • 字符串无需加引号,如果要加,'  '与""表示字符串内容 会被 转义/不转义

(比如:单引号会将 \n 作为字符串输出,双引号会将\n作为换行输出,,,\n本来就是换行,“”不转义,不对其操作,所有他还是换行!)

数据类型:

  • 字面量:单个的、不可再分的值。date、boolean、string、number、null
k: v
  • 对象:键值对的集合。map、hash、set、object
行内写法:  k: {k1:v1,k2:v2,k3:v3}
#或
k: 
  k1: v1
  k2: v2
  k3: v3
  • 数组:一组按次序排列的值。array、list、queue
行内写法:  k: [v1,v2,v3]
#或者
k:
 - v1
 - v2
 - v3

实例:

两个实体类:

================person.java================
@ConfigurationProperties(prefix = "person")
@Component
@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;
}
==================pet.java================
@Data
@Component
@ToString
public class Pet {
    private String name;
    private int age;
}

application.yml

person:
  username: zhangsan
  boss: true
  birth: 2000/12/9
  age: 20
  pet:
    name: adag
    age: 20
# interests: [java,go]
  interests:
    - java
    - go
  animal: [dog,cat]
  score: {english:80,math:90}
  salary:
    - 8000.66
    - 12000.89
  allPets:
    big:
      - {name: bigdog,age: 8}
      - name: bigcat
        age: 55
      - name: bigmk
        age: 12
    small:
      - {name: smalldog,age: 20}
      - name: smallcat
        age: 5

自定义类绑定的配置提示

我们自定义的类,如上面的person.java在配置文件中写的时候,没有提示,比如username,输入us,username就没有处于备选择的地方,怎么办?

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

=======目的:打包的时候不要把上面的配置类打包进去========

 <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>

userName 自动配置的时候 为 user-name

阅读剩余
THE END