【参数校验】 自定义校验器 (实现ConstraintValidator)
日常工作中写接口时,往往需要校验前端传来的枚举状态码,例如"1","2"等等,
这里使用java 303规范的参数校验框架封装一个自定义参数校验器:
/** * @author: yq * @date: 2020/9/22 22:15 * @description 自定义参数校验注解,加在指定的需要校验的字段上 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.PARAMETER}) @Constraint(validatedBy = CustomerValidatorClass.class) //这里需要指定参数校验的具体实现类 public @interface CustomerValidator { String[] value() default {}; String message() default "flag is not found"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
/** * @author: yq * @date: 2020/9/22 22:14 * @description 通用自定义参数校验器实现 */ public class CustomerValidatorClass implements ConstraintValidator<CustomerValidator,String> { private String[] values; @Override public void initialize(CustomerValidator validator) { this.values= validator.value(); } @Override public boolean isValid(String value, ConstraintValidatorContext context) { AtomicBoolean atomicValid = new AtomicBoolean(false); if (value ==null) { //当状态为空时使用默认值 return true; } Stream.of(values).filter(x->x.equals(value)).findFirst().ifPresent(s -> atomicValid.set(true)); return atomicValid.get(); } }
测试:
/** * 测试自定义参数校验 @CustomerValidator CustomerValidator.class */ @PostMapping("/test/validator") public Result testValidator(@RequestBody @Valid TestValidatorDTO dto){ System.out.println(dto); return Result.success(); }
/** * @author: yq * @date: 2020/9/22 22:24 * @description */ @Data public class TestValidatorDTO { /** 参数校验测试 */ @CustomerValidator(value = {"1","2"}) private String code; }
使用postman测试发现,当数据为"1"或者"2"时,校验通过,当参数为其他值时,参数校验失败,抛出参数校验异常