Spring Boot 3.x特性-类型安全的配置属性
系列文章目录
系列文章:Spring Boot 3.x 系列教程
文章目录
- 系列文章目录
- 前言
- 一、 JavaBean属性绑定
- 二、构造函数绑定
- 三、@ConfigurationProperties
-
- 1.启用@ConfigurationProperties注解
- 2.使用@ConfigurationProperties注解
- 3.@ConfigurationProperties校验
- 四、三方配置
- 五、宽松绑定
-
- 绑定Maps
- 从环境变量绑定
- 六、合并复杂类型
- 七、属性转换
-
- 转换Duration
- 转换Period
- 转换数据大小
- 八、@ConfigurationProperties vs @Value
- 总结
前言
SpringBoot 提供@ConfigurationProperties和@Value注解,可以把属性绑定到JavaBean中。
使用@Value("${property}")注解注入配置属性有时可能很麻烦,特别是在处理多个属性或数据本质上是分层嵌套的情况。
一、 JavaBean属性绑定
通过@ConfigurationProperties注解可以把属性配置文件内容绑定到JaveBean中,如下所示:
@Component
@ConfigurationProperties("my.service")
public class MyProperties {
private boolean enabled;
private InetAddress remoteAddress;
private final Security security = new Security();
// getters / setters...
public static class Security {
private String username;
private String password;
private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
// getters / setters...
}
}