自己实现一个注解


@Target( { METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = UserNameValidator.class)
@Documented
public @interface NotRepeat {

String message() default "用户名已存在";

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

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

其中@Constraint注解表明校验类,也就是说真正的校验在UserNameValidator这个类里面


public class UserNameValidator implements ConstraintValidator<NotRepeat, String> {

public void initialize(NotRepeat constraintAnnotation) {
// TODO Auto-generated method stub

}

public boolean isValid(String value, ConstraintValidatorContext context) {
if (value.equals("123") || value.equals("admin")) {
return false;
}
return true;
}

}

自定义校验value值不为123或者不为admin

 

@NotRepeat

private String value

 

posted on 2019-10-29 15:37  一只二傻子  阅读(537)  评论(0编辑  收藏  举报

导航