SpringBoot新增自定义校验配置
SpringBoot
新增自定义校验
背景
新增自定义参数校验,方便扩展,同时增加全局异常捕获配置将参数校验中的异常信息返回给前端
操作步骤
- 参考@Max校验增加@Range注解,需要增加groups和payload属性,否则会报错
- @Constraint注解中
validateBy
必须指定校验类,否则会报错
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { RangeValidator.class })
public @interface Range {
String message() default "not in range";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
int min();
int max();
}
- 增加校验器做判断,此处做了简化处理,@Max中使用了泛型支持多种数据类型校验,而@Range只支持Integer类型校验
public class RangeValidator implements ConstraintValidator<Range, Integer> {
public long min;
public long max;
@Override
public void initialize(Range range) {
this.min = range.min();
this.max = range.max();
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
if ( value == null ) {
return true;
}
return value >= min && value <= max;
}
}
- 增加全局异常捕获参数校验异常
@RestControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler(MethodArgumentNotValidException.class)
public RetJson handleValidationException(MethodArgumentNotValidException e) {
List<ObjectError> errors = e.getBindingResult().getAllErrors();
StringBuilder builder = new StringBuilder();
errors.forEach(error -> builder.append(error.getDefaultMessage()).append(";"));
return RetJson.err(builder.toString());
}
}
测试结果