實現自定義校驗注解,ConstraintValidator接口
/**
* Defines the logic to validate a given constraint {@code A}
* for a given object type {@code T}.
* <p>
* Implementations must comply to the following restriction:
* <ul>
* <li>{@code T} must resolve to a non parameterized type</li>
* <li>or generic parameters of {@code T} must be unbounded
* wildcard types</li>
* </ul>
* <p>
* The annotation {@link SupportedValidationTarget} can be put on a
* {@code ConstraintValidator} implementation to mark it as supporting
* cross-parameter constraints. Check out {@link SupportedValidationTarget}
* and {@link Constraint} for more information.
*
* @param <A> the annotation type handled by an implementation
* @param <T> the target type supported by an implementation
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
*/
public interface ConstraintValidator<A extends Annotation, T> {
/**
* Initializes the validator in preparation for
* {@link #isValid(Object, ConstraintValidatorContext)} calls.
* The constraint annotation for a given constraint declaration
* is passed.
* <p>
* This method is guaranteed to be called before any use of this instance for
* validation.
* <p>
* The default implementation is a no-op.
*
* @param constraintAnnotation annotation instance for a given constraint declaration
*/
default void initialize(A constraintAnnotation) {
}
/**
* Implements the validation logic.
* The state of {@code value} must not be altered.
* <p>
* This method can be accessed concurrently, thread-safety must be ensured
* by the implementation.
*
* @param value object to validate
* @param context context in which the constraint is evaluated
*
* @return {@code false} if {@code value} does not pass the constraint
*/
boolean isValid(T value, ConstraintValidatorContext context);
}
1.initialize方法
會在校驗實例化后被調用,一般用於做些初始化工作。
2.isValid方法
實際執行驗證的方法,第一個參數獲取的是字段或對象實際對應的值,取決於類的枚舉限定類型。第二個參數是ConstraintValidatorContext,上下文可以做些默認的設置。
本文使用自定義校驗注解驗證身份證是否符合要求。
@Constraint(validatedBy = IdCardValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IdCard {
String message() default "身份證不合法";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class IdCardValidator implements ConstraintValidator<IdCard, String> {
@Override
public void initialize(IdCard constraintAnnotation) {
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
return IdCardUtils.checkIdCard(s);
}
}
@IdCard
private String idCard;
