@ListValue(vals={0,1})
private Integer showStatus;
1)、编写一个自定义校验注解
@Documented
@Constraint(validatedBy = {ListValueValidatorForInteger.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface ListValue {
String message() default "{com.atguigu.common.valid.ListValue.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int[] vals() default {};
}
编写配置文件com.atguigu.common.valid.ListValue.message
com.atguigu.common.valid.ListValue.message=必须提交指定的值
2)、编写一个自定义校验器
public class ListValueValidatorForInteger implements ConstraintValidator<ListValue, Integer> {
private Set<Integer> set = new HashSet<>();
@Override
public void initialize(ListValue constraintAnnotation) {
//遍历需要校验的vals
int[] vals = constraintAnnotation.vals();
for (int val : vals) {
//装填到set
set.add(val);
}
}
//判断是否校验成功 value:需要校验的值
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
}
}
3)、关联自定义的校验器和自定义的注解
@Constraint(validatedBy = {ListValueValidatorForInteger.class})