学科分类
目录
Spring Boot开发

使用@ConfigurationProperties注入属性

Spring Boot提供的@ConfigurationProperties注解用来快速、方便地将配置文件中的自定义属性值批量注入到某个Bean对象的多个对应属性中。假设现在有一个配置文件,如果使用@ConfigurationProperties注入配置文件的属性,示例代码如下:

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private int id;      
    // 属性的setXX()方法
    public void setId(int id) {
        this.id = id;
    }
}

上述代码使用@Component和@ConfigurationProperties(prefix = “person”)将配置文件中的每个属性映射到person类组件中。

需要注意的是,使用@ConfigurationProperties注解批量注入属性值时,要保证配置文件中的属性与对应实体类的属性一致,否则无法正确获取并注入属性值。

点击此处
隐藏目录