10.SpringBoot学习笔记

YAML配置文件值获取

Posted by Chen Xingxu on June 20, 2020

SpringBoot学习笔记(十)–YAML配置文件值获取

配置文件

person:
    lastName: hello
    age: 18
    boss: false
    birth: 2020/6/6
    maps: {k1: v1,k2: v2}
    lists:
      - lisi
      - zhaoliu
    dog:
      name: 小狗
      age: 3

javaBean

package com.atguigu.springboot.bean;
/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:要求SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":选取配置文件中对应的属性,进行一一映射
 *
 * 只有这个组件是容器中的组件,才能使用容器提供的功能
 * 比如@ConfigurationProperties功能;
 *  @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
 *
 */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
}
package demo.yangxu.springboot.bean;
public class Dog {
    private String name;
    private Integer age;
}

测试类

package demo.yangxu.springboot;
//SpringBoot单元测试
@SpringBootTest
class Springboot02ConfigApplicationTests {
    @Autowired
    Person person;

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

测试结果

可以导入配置文件处理器,这样编写配置的时候就有提示了

<!--导入配置文件处理器,配置文件进行绑定就会有提示-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>