参考文献

@ConfigurationProperties

  • @ConfigurationProperties 通过setter和构造器来设置field的值, 并且支持级联绑定属性
  • 配置文件中的属性个数可以和POJO中的field个数不一样, 如果这样那么field就使用默认值或是初始值
  • 要想使@ConfigurationProperties生效, 可以通过@Component, 或是在配置类上使用@EnableConfigurationProperties, 并且指定value来使properties文件的值自动注入到对应pojo的属性中(同时会将该POJO注入到IoC)
  • @ConfigurationProperties 不能与@EnableConfigurationProperties 一起标注在同一个类上
  • 可以在@ConfigurationProperties标注的类上使用@Validated在来校验field的绑定
  • 如果一个类标明了@ConfigurationProperties, 不会对内部类生效, 需要另外配置(因为内部类和外部类编译后是两不同的类)
  • @NestedConfigurationProperties没有任何实际功能, 用于表示@ConfigurationProperties标注的类中的field不是一个单一的值, 常与有初始值的复杂对象一起出现
  • @ConfigurationProperties可以和@PropertySource一起使用, 这样就可以不用一个一个@Value

注意点

  • 如果@ConfigurationProperties所注的类可以被Springboot扫描并添加进容器中作为Bean(比如使用@Component等注解,或者配置扫描该类所在包等手段),那么Spring容器会自动使该类上的@ConfigurationProperties生效,创建一个该类的实例,然后把对应配置属性绑定进该实例,再把该实例作为Bean添加进Spring容器。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    package com.med3d.athena.propreties;

    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.NestedConfigurationProperty;
    import org.springframework.stereotype.Component;

    /**
    * 系统配置
    */
    @Component
    @ConfigurationProperties(prefix = "athena.business")
    @Data
    public class BusinessProperties {

    /**
    * 数据相关配置
    */
    @NestedConfigurationProperty
    private DataProperties dataProperties;

    /**
    * OSS配置
    */
    @NestedConfigurationProperty
    private OssProperties ossProperties;
    }

  • 如果该类只使用了@ConfigurationProperties注解,然后该类没有在扫描路径下或者没有使用@Component等注解,导致无法被扫描为Bean,那么就必须在配置类上使用@EnableConfigurationProperties注解去指定这个类,这个时候就会让该类上的@ConfigurationProperties生效,然后作为Bean添加进Spring容器中

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    @Component
    @ConfigurationProperties(prefix = "athena.business")
    @Data
    public class BusinessProperties {

    /**
    * 数据相关配置
    */
    @NestedConfigurationProperty
    private DataProperties dataProperties;
    }

    @Configuration
    @EnableConfigurationProperties(BusinessProperties.class)
    public class BusinessConfiguration {

    }