我想创建一个@LengthIfNotBlank(min=,max=)
基于 Hibernates约束的自定义@Length
约束:
@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = LengthIfNotBlankValidator.class)
@Documented
public @interface LengthIfNotBlank {
String message() default "{com.mycompany.LengthIfNotBlank}";
Class<? extends Payload>[] payload() default {};
int max() default Integer.MAX_VALUE;
Class<?>[] groups() default {};
int min() default 0;
}
public class LengthIfNotBlankValidator extends LengthValidator {
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
return StringUtils.isBlank(value) || super.isValid(value, constraintValidatorContext);
}
}
例外:
[java] javax.validation.ValidationException: Unable to initialize com.example.constraints.LengthIfNotBlankValidator
[java] Caused by: java.lang.ClassCastException: $Proxy32 cannot be cast to org.hibernate.validator.constraints.Length
更新
仍然得到这个例外:-(
public class LengthIfNotBlankValidator extends LengthValidator {
public void initialize(LengthIfNotBlank parameters) {
Map<String,Object> elements = new HashMap<String,Object>();
elements.put("message", parameters.message());
elements.put("payload", parameters.payload());
elements.put("groups", parameters.groups());
elements.put("min", parameters.min());
elements.put("max", parameters.max());
AnnotationDescriptor<Length> descriptor = AnnotationDescriptor.getInstance(Length.class, elements);
Length length = AnnotationFactory.create(descriptor);
super.initialize(length);
}
@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
return StringUtils.isBlank(value) || super.isValid(value, constraintValidatorContext);
}
}