Spring Boot请求体传对象列表时校验注解失效问题求助
Spring Boot请求体传递对象列表时校验注解失效的解决方法
问题场景
当你通过@RequestBody接收单个RepresentativeForManyBranchesRequest对象时,@Required、@Length等校验注解能正常生效,但接收List<RepresentativeForManyBranchesRequest>列表时,列表内对象的校验规则完全失效。
核心原因
- Spring默认未开启方法级参数校验,
@Valid注解作用于集合时,需要方法级校验支持才能遍历集合元素执行校验逻辑。 @Required并非JSR-380标准校验注解,Spring的校验器可能无法识别该注解的校验规则。
解决步骤
1. 开启方法级校验
在Controller类或Spring Boot启动类上添加@Validated注解,触发Spring的方法参数校验机制:
@RestController @Validated // 必须添加此注解 @RequestMapping("/your-base-path") public class BranchController { @PatchMapping("/branches") public MicApiResponse<Void> updateForManyBranches( @RequestBody @Valid List<RepresentativeForManyBranchesRequest> req) throws MicClientException { service.updateForManyBranches(req); return MicApiResponse.succeed(); } }
2. 替换为标准校验注解
将非标准的@Required替换为JSR-380标准注解(如@NotNull、@NotBlank),确保Spring校验器能识别规则:
@Getter @Setter @NoArgsConstructor @AllArgsConstructor public class RepresentativeUserForManyBranchesRequest { private String id; @NotNull(message = "userId不能为空") private String userId; @NotBlank(message = "name不能为空") @Length(min = 1, max = 100, message = "name长度需在1-100字符之间") private String name; @NotBlank(message = "position不能为空") @Length(min = 1, max = 100, message = "position长度需在1-100字符之间") private String position; }
3. 捕获校验异常(可选)
添加全局异常处理器,统一处理校验失败的情况:
@RestControllerAdvice public class GlobalValidationExceptionHandler { @ExceptionHandler(ConstraintViolationException.class) public MicApiResponse<Void> handleValidationErrors(ConstraintViolationException e) { String errorMsg = e.getConstraintViolations() .stream() .map(ConstraintViolation::getMessage) .collect(Collectors.joining("; ")); return MicApiResponse.fail(errorMsg); } }
验证逻辑
修改后,当请求体中的列表存在不符合校验规则的元素时,Spring会直接抛出ConstraintViolationException,并通过全局异常处理器返回自定义错误响应,确保每个列表元素的校验规则都被执行。
内容的提问来源于stack exchange,提问作者Nghi Hoàng Đức
相关产品推荐
相关产品推荐

