使用注解校验入参@ValuesInEnum
声明
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(ValuesInEnum.List.class)
@Constraint(validatedBy = ValueInEnumValidator.class)
public @interface ValuesInEnum {
String message() default “”;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
/*** 支持的枚举值 */
String[] enums() default {};
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
ValuesInEnum[] value();
}
}
实现
public class ValueInEnumValidator implements ConstraintValidator<ValuesInEnum, String> {
private List enumStringList;
@Override
public void initialize(ValuesInEnum constraintAnnotation) {
enumStringList = Arrays.asList(constraintAnnotation.enums());
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
if(value == null) {
return true;
}
return enumStringList.contains(value);
}
}
使用:
@ValuesInEnum(enums = {“Y”,“N”},message = “isFlag入参错误!”)
private String isFlag = “N”;