SpringBoot3.4配置校验新特性的用法详解

2025-05-14 04:19:50 111
魁首哥

配置属性验证增强亮点

spring boot 3.4 对配置校验支持进行了全面升级,核心亮点包括:

  • 支持jakarta.validation全套标准注解(如@notnull@email@pattern等)
  • 嵌套对象、集合元素深度校验支持
  • 启动阶段校验失败,ide友好提示,快速定位问题
  • 自动生成更完善的开发时元信息(metadata)

可以说,从易用性到严谨性,都有了质的飞跃!

基本用法示例

定义配置类

以用户配置为例:

package com.icoderoad.demo.config;


import jakarta.validation.valid;
import jakarta.validation.constraints.*;
import org.springframework.boot.context.properties.configurationproperties;
import org.springframework.validation.annotation.validated;


import java.util.list;


@validated
@configurationproperties(prefix = "app.user")
public class userproperties {


    @notblank(message = "用户名不能为空")
    private string username;


    @email(message = "邮箱格式不正确")
    private string email;


    @min(value = 18, message = "年龄不能小于18岁")
    private integer age;


    @valid
    private address address;


    @size(min = 1, message = "至少需要一个角色")
    private list<@notblank(message = "角色名称不能为空") string> roles;


    // address是嵌套对象,需要加@valid
    public static class address {
        @notblank(message = "城市不能为空")
        private string city;


        @pattern(regexp = "\d{6}", message = "邮编必须是6位数字")
        private string zipcode;


        // getter/setter
        public string getcity() {
            return city;
        }
        public void setcity(string city) {
            this.city = city;
        }
        public string getzipcode() {
            return zipcode;
        }
        public void setzipcode(string zipcode) {
            this.zipcode = zipcode;
        }
    }


    // getter/setter
    public string getusername() {
        return username;
    }
    public void setusername(string username) {
        this.username = username;
    }
    public string getemail() {
        return email;
    }
    public void setemail(string email) {
        this.email = email;
    }
    public integer getage() {
        return age;
    }
    public void setage(integer age) {
        this.age = age;
    }
    public address getaddress() {
        return address;
    }
    public void setaddress(address address) {
        this.address = address;
    }
    public list getroles() {
        return roles;
    }
    public void setroles(list roles) {
        this.roles = roles;
    }
}

配置 application.yml

app:
  user:
    username: "张三"
    email: "zhangsan@example.com"
    age: 25
    address:
      city: "上海"
      zipcode: "200000"
    roles:
      - "admin"
      - "user"

注入使用

在你的服务中注入:

package com.icoderoad.demo.service;


import com.example.demo.config.userproperties;
import org.springframework.stereotype.service;


@service
public class userservice {


    private final userproperties userproperties;


    public userservice(userproperties userproperties) {
        this.userproperties = userproperties;
    }


    public void printuserinfo() {
        system.out.println("用户名:" + userproperties.getusername());
        system.out.println("邮箱:" + userproperties.getemail());
    }
}

嵌套对象与集合元素深度校验

注意,在嵌套对象上必须标注@valid,才能对子属性继续校验。集合元素(如list)同样支持元素级校验注解

这让配置类的约束更加细粒度、安全。

启动阶段即校验失败

如果配置不符合要求,比如漏填username、邮箱格式错误、年龄不足18岁、角色列表为空等,spring boot 启动时就会直接报错

示例错误日志:

***************************
application failed to start
***************************

description:

binding to target [bindable@xxx type = com.icoderoad.demo.config.userproperties] failed:

property: app.user.username
value:
reason: 用户名不能为空

property: app.user.email
value: not-an-email
reason: 邮箱格式不正确

非常直观,能第一时间发现配置问题,避免服务上线后隐患!

开发时元信息增强

配合 spring boot 的spring-boot-configuration-processor插件,还能自动生成提示补全信息(ide 中.yml配置智能提示)!

pom.xml配置:


org.springframework.boot
spring-boot-configuration-processor
true

编译后,会生成meta-inf/spring-configuration-metadata.json,供 ide 智能补全参考。

注意事项

  • @configurationproperties
    必须配合@validated
  • 嵌套对象字段要加@valid
  • 集合元素校验,需要在泛型上加注解
  • 使用 jakarta validation 标准注解(spring boot 3.x 默认使用 jakarta)

扩展:错误处理更友好(自定义异常消息格式)

默认启动校验失败时,spring boot 抛出bindvalidationexception,信息虽然完整但略显杂乱。为了让错误提示更专业友好,我们可以自定义异常处理。

定义友好的异常类

package com.icoderoad.demo.exception;


/**
 * 自定义配置校验异常
 */
public class configvalidationexception extends runtimeexception {


    public configvalidationexception(string message) {
        super(message);
    }
}

编写异常处理器

通过beanfactorypostprocessor统一拦截配置阶段的校验错误:

package com.icoderoad.demo.exception;


import org.springframework.beans.beansexception;
import org.springframework.beans.factory.config.beanfactorypostprocessor;
import org.springframework.boot.context.properties.bind.bindvalidationexception;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.validation.objecterror;


import java.util.stream.collectors;


@configuration
public class configvalidationexceptionhandler {


    @bean
    public static beanfactorypostprocessor configurationpropertiesvalidator() {
        return beanfactory -> {
            try {
                // 手动触发bean初始化
            } catch (beansexception ex) {
                throwable cause = ex.getcause();
                if (cause instanceof bindvalidationexception bindvalidationexception) {
                    string errormessages = bindvalidationexception.getvalidationerrors()
                            .getallerrors()
                            .stream()
                            .map(objecterror::getdefaultmessage)
                            .collect(collectors.joining("; "));
                    throw new configvalidationexception("配置属性校验失败:" + errormessages);
                }
                throw ex;
            }
        };
    }
}

逻辑解释:

  • 捕获bindvalidationexception
  • 提取所有校验失败信息
  • 使用;拼接成简洁可读的文本
  • 抛出我们的configvalidationexception

示例效果

比如你的配置错误如下:

app:
  user:
    username: ""
    email: "wrong"
    age: 15
    address:
      city: ""
      zipcode: "12abc"
    roles:
      - ""

启动时抛出的错误变成:

配置属性校验失败:用户名不能为空; 邮箱格式不正确; 年龄不能小于18岁; 城市不能为空; 邮编必须是6位数字; 角色名称不能为空

  • 信息集中、简洁直观
  • 一次性列出所有问题,快速修复
  • 适合前后端、测试同事快速理解

总结

spring boot 3.4 配置属性验证:

  • 验证能力更强大覆盖深度校验、集合元素校验
  • 开发体验更极致启动即校验,ide智能提示
  • 错误处理更优雅可自定义异常格式
  • 提升整体代码质量避免配置隐患上线

在实际项目中,推荐配合自定义异常机制,打造更加专业可靠的配置校验体系!

到此这篇关于springboot3.4配置校验新特性的用法详解的文章就介绍到这了,更多相关springboot配置校验内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

分享
海报
111
上一篇:在 Spring Boot 中实现异常处理最佳实践 下一篇:Java并发编程之如何优雅关闭钩子Shutdown Hook

忘记密码?

图形验证码