转自:https://www.codeneko.cn/?p=175

在SpringBoot使用@ConfigurationProperties注解读取yml/properties配置文件参数

1. 添加依赖

在pom文件中添加依赖

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

2. 在yml/properties文件中添加配置

这里使用yml格式配置文件配置

config:
  entity:
    cat:
      name: Tomcat
      sex: male
      age: 9

3. 创建类

创建一个类,并且添加注解@ConfigurationProperties和指定的prefix。

类必须实现setter方法,否则无法配置对象对应的属性变量!!!

@ConfigurationProperties(prefix = "config.entity.cat")
@Component
public class Cat {

    private String name;
    private String sex;
    private int age;
    private String family;

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

    public void setSex(String sex) {
        this.sex = sex;
    }

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

    public void setFamily(String family) {
        this.family = family;
    }
    // 省略getter
    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", family='" + family + '\'' +
                '}';
    }
}

4. 测试

控制台输出对象信息:

Cat{name='Tomcat', sex='male', age=9, family='null'}

可以看到在配置文件中所配置的参数都正确的注入到Cat对象中,而在配置文件中没有配置的family属性默认为null。

posted on 2020-09-21 14:42  Sharpest  阅读(2667)  评论(0编辑  收藏  举报