美文网首页
hibernate Validator自定义注解

hibernate Validator自定义注解

作者: Burning_6c93 | 来源:发表于2019-01-30 23:41 被阅读0次

如何自定义注解,加入自己的校验逻辑

@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;
    }
}

相关文章

网友评论

      本文标题:hibernate Validator自定义注解

      本文链接:https://www.haomeiwen.com/subject/rophsqtx.html