在 SpringBoot 工程配置文件 application.properties 或 application.yaml 中声明的配置,除了可以通过 @Value 注解单个获取外,还可以通过 @ConfigurationProperties 注解批量获取相同前缀的配置。

下面通过 application.yaml 配置文件示例。

简单类型配置详解

如 String 以及基本数据类型的配置,可以直接通过对应名称绑定:

  1. profile:
  2. user-name: zhangsan
  3. age: 12
  4. email: zhangsan@profile.com
  5. enable: true

配置类如下:

  1. @Data
  2. @Validated
  3. @Component
  4. @ConfigurationProperties(prefix = "profile")
  5. public class StrategyConfig {
  6. @NotEmpty
  7. private String userName = "zhangsan";
  8. @NotNULL
  9. private Integer age = 12;
  10. @Email
  11. private String email = "zhangsan@profile.com";
  12. private Boolean enable = true;
  13. }
  1. 可以在后面初始化值指定默认值,且属性必须有 setter 方法;
  2. 可以通过 @Validated 注解进行 JSR303 校验;
  3. 除了通过 @Component 启用配置外,还可以通过 Java 配置类声明 @Bean 和在配置类或启动类添加 @EnableConfigurationProperties(StrategyConfig.class) 启用;
  4. 支持宽松绑定,下面的属性都可以绑定到 userName 上;
    1. profile.userName=zhangsan
    2. profile.username=zhangsan
    3. profile.user-name=zhangsan
    4. profile.user_name=zhangsan
    5. profile.USER_NAME=zhangsan

    复杂类型属性

    profile:
    user:
     user-name: zhangsan
     age: 12
     email: zhangsan@profile.com
     enable: true
    
    ```java @Data @Component @ConfigurationProperties(prefix = “profile”) public class StrategyConfig { @NestedConfigurationProperty private UserInfo user; }

@Data public class UserInfo { private String userName = “zhangsan”; private Integer age = 12; private String email = “zhangsan@profile.com”; private Boolean enable = true; }

<a name="WOSQU"></a>
# 复杂类型列表
```yaml
service:
  data-lists:
    - service-name: Mysql
      service-desc: 关系型数据库
      service-status: 0
      service-path-name: mysql
      service-code: 1000
    - service-name: Redis
      service-desc: 非关系型数据库
      service-status: 0
      service-path-name: redis
      service-code: 1001
@Data
@Component
@ConfigurationProperties(prefix = "service")
public class ServiceListConfiguration {

    public List<DataList> dataLists;

    @Data
    public static class DataList {
        private String serviceName;
        private String serviceDesc;
        private Integer serviceStatus;
        private String servicePathName;
        private Integer serviceCode;
    }
}