找不到类型的验证器:枚举

时间:2015-11-17 06:59:52

标签: java spring validation enums

我对Enumaration的验证有例外:

  

WARN   org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver:186    - 处理程序执行导致异常:HV000030:找不到类型为:enum.YesNo

的验证程序

所有课程如下:

public enum YesNo {
    YES("Yes"), NO("No");
    private String value;

    YesNo(final String value) {
        this.value = value;
    }
}

public class Bean {
    @NotNull
    @EnumValidator(enumClazz = YesNo.class)
    private YesNo yesno;
}

@Documented
@Constraint(validatedBy = EnumValueValidator.class)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnumValidator {
    Class<? extends Enum<?>>enumClazz();

    String message() default "Value is not valid";

    Class<?>[]groups() default {};

    Class<? extends Payload>[]payload() default {};
}

public class EnumValueValidator implements ConstraintValidator<EnumValidator, String> {
    List<String> valueList = null;

    @Override
    public boolean isValid(final String value, final ConstraintValidatorContext context) {
        if (!valueList.contains(value.toUpperCase())) {
            return false;
        }
        return true;
    }

    @Override
    public void initialize(final EnumValidator constraintAnnotation) {
        valueList = new ArrayList<String>();
        Class<? extends Enum<?>> enumClass = constraintAnnotation.enumClazz();

        @SuppressWarnings("rawtypes")
        Enum[] enumValArr = enumClass.getEnumConstants();

        for (@SuppressWarnings("rawtypes")
        Enum enumVal : enumValArr) {
            valueList.add(enumVal.toString().toUpperCase());
        }
    }
}

0 个答案:

没有答案