Spring Boot中获取yml配置文件的值

1.根据配置文件的属性创建一个bean实体类

server:
  port: 8081

person:
  name: boot
  age: 18
  date: 2019/04/22

  maps: {k1: v1,k2: v2}
  list: [e1,e2,e3]
  animal:
    name: dog
    age: 3

Person 实体类;

package com.myproject.springboot.bean;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class Person {
    private String name;
    private Integer age;
    private Date birth;

    private Map maps;
    private List list;
    private Animal animal;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public List getList() {
        return list;
    }

    public void setList(List list) {
        this.list = list;
    }

    public Animal getAnimal() {
        return animal;
    }

    public void setAnimal(Animal animal) {
        this.animal = animal;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birth=" + birth +
                ", maps=" + maps +
                ", list=" + list +
                ", animal=" + animal +
                '}';
    }
}
 
  

Animal 实体类;

package com.myproject.springboot.bean;

public class Animal {
    private String name;
    private Integer age;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.结合注解@ConfigurationProperties(prefix = "person")将bean里面的属性和yml中的属性自动绑定,点开IDEA工具弹出的提示;

Spring Boot中获取yml配置文件的值_第1张图片

3.添加依赖 配置文件处理器 到pom.xml文件

Spring Boot中获取yml配置文件的值_第2张图片

Spring Boot中获取yml配置文件的值_第3张图片

4.再使用@Component注解表示把这个组件添加到容器中,如此才能生效

Spring Boot中获取yml配置文件的值_第4张图片

5.进入到单元测试里面,测试获取参数是否正常

Spring Boot中获取yml配置文件的值_第5张图片

 

 

你可能感兴趣的:(Spring-Boot)