在 Controller 类上 加上@Validated。在需要校验的参数上加上 @Valid 。 就可以校验list里的实体类的属性
还需要在统一异常处理类中添加异常处理
/**
* 参数校验异常类
*
* @param exception
* @return
* @author 刘朋
* <br/>date 2020-04-15
*/
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public ResponseMessage handlerConstraintViolationException(ConstraintViolationException exception) {
log.warn(exception.getMessage(), exception);
Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
StringBuilder strBuilder = new StringBuilder();
for (ConstraintViolation<?> constraintViolation : constraintViolations) {
String message = constraintViolation.getMessage();
strBuilder.append(message).append("\n");
}
return Result.error(ResponseMessageCodeEnum.VALID_ERROR.getCode(), strBuilder.toString());
}