定义注解:
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintorMethod.class)
public @interface MyConstraintVilidator {
String message() ; //验证不通过的时候输入
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
其中:@Constraint(validatedBy = MyConstraintorMethod.class) 这是我们判断的逻辑这里面
@Slf4j
public class MyConstraintorMethod implements ConstraintValidator<MyConstraintVilidator, Object> {
@Autowired
private PersonService personService;
@Override
public void initialize(MyConstraintVilidator myConstraintVilidator) {
log.info("MyConstraintVilidatorMethod 初始化");
}
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
if (StringUtils.isEmpty(o)) {
return false; //验证不通过
}
personService.greeting("jaychou");
return true;
}
}
在字段里面
@MyConstraintVilidator(message = "xxxx")
private String testConstraint;
这算是一个模板吧