本文共 1206 字,大约阅读时间需要 4 分钟。
步骤:
1.定义注解:
import javax.validation.Constraint;import javax.validation.Payload;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})@Retention(RetentionPolicy.RUNTIME)@Constraint(validatedBy = MyValidatorClass.class)public @interface MyValidator { String message(); Class [] groups() default {}; Class [] payload() default {};}
2.定义校验类
import javax.validation.ConstraintValidator;import javax.validation.ConstraintValidatorContext;/** * MyValidator,自定义注解 * String 标注在String类型的字段上,传过来的值是String类型 */public class MyValidatorClass implements ConstraintValidator{ /** * 初始化注解时执行的 * @param myValidator */ @Override public void initialize(MyValidator myValidator) { } /** * 真正的校验逻辑 * @param o * @param constraintValidatorContext * @return */ @Override public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) { return false; }}
3.使用
转载地址:http://tyzeo.baihongyu.com/