自定义校验注解ConstraintValidator

自定义校验注解ConstraintValidator

系统执行业务逻辑之前,会对输入数据进行校验,检测数据是否有效合法的。所以我们可能会写大量的if else等判断逻辑,特别是在不同方法出现相同的数据时,校验的逻辑代码会反复出现,导致代码冗余,阅读性和可维护性极差。

自定义注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
@Constraint(validatedBy = AgeConstraint.class)   // 指定一个校验处理类
public @interface AgeMin {
    Integer min() default 18; // 最小年龄
  	Integer max() default 35; // 最大年龄
    String message() default "年龄不符合";   // 校验失败返回信息
  
    // 将validator进行分类,不同的类group中会执行不同的validator操作
    Class<?>[] groups() default {};
    // 主要是针对bean,很少使用
    Class<? extends Payload>[] payload() default {};
}

校验处理类

需要实现ConstraintValidator接口

public class AgeConstraint implements ConstraintValidator<AgeMin,Integer> {

    private Integer min;
  	private Integer max;

    @Override
    public void initialize(AgeMin constraintAnnotation) {   // 参数为自定义注解,进行初始化参数
        this.min = constraintAnnotation.min();
      	this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
      // integer为注解标注位置的值	
      if (integer == null){
          return true;
        }
        if (integer>=min && integer<=max){
            return true;
        }
        return false;
    }
}

使用自定义校验注解

定义一个User

@Data
public class User {
    private String name;
  	
  	@AgeMin( min = 18, max =30 )  // 使用自定义校验注解
    private Integer age;
}

Controller中的方法

@RestController
public class Hello {

    @RequestMapping(value = "hello")
    public User hello(@Valid User user){  // 注意!要加上@Valid
        return user;
    }
}

在全局异常处理中进行校验失败异常处理

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        log.error(e.getMessage(), e);

        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            List<ObjectError> allErrors = ex.getAllErrors();
            ObjectError error = allErrors.get(0);
            String defaultMessage = error.getDefaultMessage();
            return defaultMessage;
        }  else {
            return "error";
        }
    }
}
posted @ 2025-03-27 20:46  mango0219  阅读(84)  评论(0)    收藏  举报