注解 :@InList 用来校验属性值是否在指定数组中 是:通过校验 否:抛异常 @Constraint(validatedBy = {InListConstraintValidator.class}) 指定校验器,可以是数组 String message() default “{com.study.hsst.anno.InList.message}”:指定的默认异常信息
@Documented
@Constraint(validatedBy = {InListConstraintValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
public @interface InList {
String message() default "{com.study.hsst.anno.InList.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int[] values() default {};
}
校验器:InListConstraintValidator initialize:初始化 isValid:属性校验
public class InListConstraintValidator implements ConstraintValidator<InList, Integer> {
private final Set<Integer> statusSet = Sets.newHashSet();
@Override
public void initialize(InList constraintAnnotation) {
for (int value : constraintAnnotation.values()) {
statusSet.add(value);
}
}
@Override
public boolean isValid(Integer value, ConstraintValidatorContext context) {
return statusSet.contains(value);
}
}
resources/ValidationMessages.properties 文件名称必须为ValidationMessages.properties,否则Spring无法自动装配 key:com.study.hsst.anno.InList.message 对应@InList注解message属性default值 value:必须提交指定的值
com.study.hsst.anno.InList.message=必须提交指定的值
|