在 SpringBoot 工程配置文件 application.properties 或 application.yaml 中声明的配置,除了可以通过 @Value 注解单个获取外,还可以通过 @ConfigurationProperties 注解批量获取相同前缀的配置。
简单类型配置详解
如 String 以及基本数据类型的配置,可以直接通过对应名称绑定:
profile:
user-name: zhangsan
age: 12
email: zhangsan@profile.com
enable: true
配置类如下:
@Data
@Validated
@Component
@ConfigurationProperties(prefix = "profile")
public class StrategyConfig {
@NotEmpty
private String userName = "zhangsan";
@NotNULL
private Integer age = 12;
private String email = "zhangsan@profile.com";
private Boolean enable = true;
}
- 可以在后面初始化值指定默认值,且属性必须有 setter 方法;
- 可以通过 @Validated 注解进行 JSR303 校验;
- 除了通过 @Component 启用配置外,还可以通过 Java 配置类声明 @Bean 和在配置类或启动类添加 @EnableConfigurationProperties(StrategyConfig.class) 启用;
- 支持宽松绑定,下面的属性都可以绑定到 userName 上;
profile.userName=zhangsan
profile.username=zhangsan
profile.user-name=zhangsan
profile.user_name=zhangsan
profile.USER_NAME=zhangsan
复杂类型属性
```java @Data @Component @ConfigurationProperties(prefix = “profile”) public class StrategyConfig { @NestedConfigurationProperty private UserInfo user; }profile: user: user-name: zhangsan age: 12 email: zhangsan@profile.com enable: true
@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;
}
}