定义注解
实现一个只能输入指定状态的约束条件
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);