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

Spring Validator注解失效:空List参数未触发校验及自定义错误

解决Spring Validator注解不生效并返回自定义错误信息的方案

你的问题核心是没有触发Spring的参数校验机制,同时缺少自定义异常处理来返回你设置的错误消息,以下是具体修复步骤:

1. 触发参数校验:给请求体参数添加@Valid注解

在控制器的@RequestBody参数前加上@Valid(或@Validated,后者支持分组校验),Spring才会自动对MyRequestResult中的注解规则进行校验:

@Log4j2
@RestController(value = "apiMyController")
@RequestMapping(path = "/api/v1/someRandomeURL")
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class ExecutionResultsController {
  
  @RequestMapping(method = RequestMethod.POST)
  public ExecutionResultDTO create(@RequestBody @Valid MyRequestResult myRequestResult) throws Exception {
     myService.setName(myRequestResult.getName());
  }
}  

2. 确保引入校验依赖(Spring Boot项目)

如果是Spring Boot项目,必须引入spring-boot-starter-validation依赖,否则校验注解会被忽略。Maven依赖配置如下:

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

3. 全局捕获校验异常,返回自定义错误信息

默认情况下,Spring会返回400状态码但不会携带你设置的自定义消息,需要通过全局异常处理器捕获MethodArgumentNotValidException,提取错误信息后返回:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}

补充说明

  • @NotEmpty和@Size(min=1)对于空List的校验效果一致,保留其中一个即可(推荐@NotEmpty,语义更清晰)。
  • 如果你使用的是Spring MVC而非Spring Boot,需要手动配置LocalValidatorFactoryBean和MethodValidationPostProcessor来启用校验机制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 14:45:09