如何自定义注解,加入自己的校验逻辑
@Data
public class User {
public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView {};
@JsonView(UserSimpleView.class)
private Integer id;
@JsonView(UserSimpleView.class)
//自定义注解
@MyConstraint(message = "这是dzg第一个自定义校验注解")
private String username;
@JsonView(UserDetailView.class)
@NotBlank(message = "密码不能为空")
private String password;
@Past(message = "生日必须是过去的时间")
@JsonView(UserSimpleView.class)
private Date birthday;
}
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy =MyConstraintValidator.class)
public @interface MyConstraint {
String message();
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@Slf4j
public class MyConstraintValidator implements ConstraintValidator<MyConstraint,Object> {
@Override
public void initialize(MyConstraint constraintAnnotation) {
log.info("my Validator init");
}
@Override
public boolean isValid(Object s, ConstraintValidatorContext constraintValidatorContext) {
log.info(String.valueOf(s));
return false;
}
}
网友评论