Spring Boot 配置属性类型安全,你都了解了吗?

本文详细介绍了Spring Boot中的配置属性绑定,包括JavaBean属性绑定、构造器绑定、@ConfigurationProperties的启用方式,以及第三方配置。同时讨论了配置属性的验证和@ConfigurationProperties与@Value的区别。通过实例展示了如何实现构造函数绑定,以及如何进行条件性启用和验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Boot提供了基础设施来绑定@ConfigurationProperties类型并将它们注册为bean。可以逐个类地启用配置属性,也可以启用与组件扫描方式类似的配置属性扫描。

环境:Springboot2.4.12

准备环境

@Component
@ConfigurationProperties("pack")
public class PackProperties {
  private boolean enabled;
  private InetAddress remoteAddress;
  private final Security security = new Security();
  public boolean isEnabled() {
    return enabled;
  }
  public void setEnabled(boolean enabled) {
    this.enabled = enabled;
  }
  public InetAddress getRemoteAddress() {
    return remoteAddress;
  }
  public void setRemoteAddress(InetAddress remoteAddress) {
    this.remoteAddress = remoteAddress;
  }
  public Security getSecurity() {
    return security;
  }
  public static class Security {
    private String username;
    private String password;
    private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
    public String getUsername() {
      return username;
    }
    public void setUsername(String username) {
      this.username = username;
    }
    public String getPassword() {
      return password;
    }
    public void setPassword(String password) {
      this.password = password;
    }
    public List<String> getRoles() {
      return roles;
    }
    public void setRoles(List<String> roles) {
      this.roles = roles;
    }
    @Override
    public String toString() {
      return "Security [username=" + userna
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值