You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot控制器入参空字段优雅校验及缺失提示实现方案

Spring Boot 入参空值优雅校验方案

完全不需要手写反射、堆if/else或者switch判断,直接用Spring生态原生的Bean Validation校验框架 + @ControllerAdvice全局异常拦截就能实现,全项目通用,代码耦合度极低。

前置依赖

如果使用Spring Boot 2.3及以上版本,需要单独引入校验starter,因为该版本开始校验组件不再默认绑定在web starter中:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

步骤1:给入参字段加校验注解

使用@NotBlank注解标记需要校验的字段,该注解默认会同时拦截null值、空字符串""、纯空格字符串三种非法空值场景,正好匹配需求:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Input {

    @NotBlank
    private String name;
    @NotBlank
    private String surname;
    @NotBlank
    private String fiscalCode;
    
}

如果后续需要扩展其他校验规则(比如长度限制、格式匹配),只需要在对应字段上加@Length、@Pattern等注解即可,不需要修改业务逻辑。

步骤2:控制器层开启校验

在@RequestBody修饰的入参前添加@Valid注解,Spring会在参数绑定阶段自动执行校验逻辑,校验不通过时会直接抛出MethodArgumentNotValidException,不会进入控制器业务方法:

@PostMapping(produces = { "application/json" })
public ResponseEntity<Object> myController(@Valid @RequestBody Input myInput) {
   // 校验通过才会执行到这里,直接写业务代码即可
}

步骤3:全局异常拦截统一拼接返回提示

编写全局异常处理器,拦截校验抛出的异常,批量提取所有空值字段名,拼接成要求的提示格式返回即可,这套逻辑全项目所有接口通用:

@RestControllerAdvice
public class GlobalParamExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleParamValidationError(MethodArgumentNotValidException e) {
        // 提取所有校验不通过的字段名
        List<String> missingFields = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getField)
                .distinct()
                .toList();
        // 拼接成指定格式的提示信息
        String errorTip = String.join(", ", missingFields) + "字段缺失";
        
        // 可根据自己项目的统一返回结构调整,以下为示例
        Map<String, Object> result = new HashMap<>();
        result.put("code", 400);
        result.put("message", errorTip);
        return ResponseEntity.badRequest().body(result);
    }
}

如果传入的请求体缺失name和surname字段,就会直接返回name, surname字段缺失的提示,完全符合需求。


内容的提问来源于stack exchange,提问作者wishyouwerehere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 12:00:50