1)编写一个指定要的校验注解
@Documented
@Constraint(validatedBy = { ListValueConstraintValidator.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 { };
}
@Documented @Constraint(validatedBy = { ListValueConstraintValidator.class })
2)编写一个指定要的校验器
public class ListValueConstraintValidator implements ConstraintValidator<ListValue,Integer> {
private Set<Integer> set = new HashSet<>();
//初始化方法
@Override
public void initialize(ListValue constraintAnnotation) {
int[] vals = constraintAnnotation.vals();
for (int val : vals) {
set.add(val);
}
}
//判断是否校验成功
/**
*
* @param value 需要校验的值
* @param context
* @return
*/
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return set.contains(value);
}
}
3)关联指定要的校验器和自定义的校验的注解
@Constraint(validatedBy = { ListValueConstraintValidator.class })
@Constraint(validatedBy = { ListValueConstraintValidator.class })
//判断是否校验成功
/**
*
* @param value 需要校验的值
* @param context
* @return
*/
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {return set.contains(value);
}返回false为校验失败
true为校验成功
com.atguigu.common.valid.ListValue.message=必须提交指定的值
标签:set,自定义,ListValueConstraintValidator,校验,value,class,public From: https://blog.51cto.com/u_15786786/5785878