自定义Hibernate Validator约束
定义注解
实现一个只能输入指定状态的约束条件
import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target( { METHOD, FIELD, ANNOTATION_TYPE }) @Retention(RUNTIME) @Constraint(validatedBy = StatusValidator.class) @Documented public @interface ValidStatus { String message() default "状态错误 "; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; /** * 有效的状态值集合,默认{1,2} */ int[] value() default {1,2}; }
定义校验类
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Arrays; import java.util.List; /** * 校验状态是否属于指定状态集 (ConstraintValidator后指定的泛型对象类型为 注解类和注解注释的字段类型<ValidStatus, Integer>) */ public class StatusValidator implements ConstraintValidator<ValidStatus, Integer> { private Integer[] validStatus; @Override public void initialize(ValidStatus validStatus) { int[] ints = validStatus.value(); int n = ints.length; Integer[] integers = new Integer[n]; for (int i = 0; i < n; i++) { integers[i] = ints[i]; } this.validStatus = integers; } @Override public boolean isValid(Integer n, ConstraintValidatorContext constraintValidatorContext) { List<Integer> status = Arrays.asList(validStatus); if (status.contains(n)) { return true; } return false; } }
程序中使用
public class QueryDTO { @ValidStatus @NotNull private Integer type; //...省略n行代码 } @RestController @RequestMapping(value = "xxx") public class DemoController { //...省略n行代码 @PostMapping(value = "/testUrl") public Response<ResultVO> getXXXList(@RequestBody @Valid QueryDTO dto){ //...省略n行代码 } }
也可以这样用:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator(); Set<ConstraintViolation<QueryDTO>> constraintViolations = validator.validate(queryDTO);
本博客文章皆出于学习目的,个人总结或摘抄整理自网络。引用参考部分在文章中都有原文链接,如疏忽未给出请联系本人。另外,作为一名菜鸟程序媛,如文章内容有错误,欢迎点击博客右上方的扣扣链接指导交流。