自定义hibernate validation注解

效果和优点


先看最后效果:

public class UserEntity {

    @Password  
    private String password;
    @Email
    private String email;

}

上面使用了两个自定义的注解来验证password和email,这样做的好处是:一处定义,处处使用,要修改验证规则时,也只要修改注解就可以了。而如果自定义,使用hibernate提供的标签的话:

@Pattern(regexp="...")
private String email;

如果写了很多个类之后,突然要修改验证规则regexp,此时工作量将要大得多。

实现


首先,引入hibernate validation依赖,添加:

    <!-- hibernate validator -->
    <!-- hibernate 验证框架 -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>5.2.2.Final</version>
    </dependency>

hibernate validation是JSR的参考实现,所以,用它做bean验证。

自定义一个验证注解分为三步:

  • 创建注解(Create a constraint annotation)
  • 创建验证类(Implement a validator)
  • 定义默认错误信息(Define a default error message)

    第一步,创建注解:

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { EmailValidator.class })
public @interface Email {

    String message() default "这不是有效的电子邮件格式";
    /**
     * @return the regular expression to match
     */
    String regexp() default "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9]+\\.[a-zA-Z]{2,4}";

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

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

    /**
     * Defines several {@link Size} annotations on the same element.
     *
     * @see Size
     */
    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
    @Retention(RUNTIME)
    @Documented
    @interface List {

        Email[] value();
    }

}

通过@interface关键字来创建注解,而每一个方法就是注解的一个参数。比如上面的代码,就可以这样使用@Email(regexp="...",message="...")。其它可以不用去管,直接复制就可以了,要注意的是@Constraint(validatedBy = { EmailValidator.class }),这里指定注解的验证类,根据实际替换类名。

第二步,创建验证类:

public class EmailValidator implements ConstraintValidator<Email, String>{

    private String regexp;

    @Override
    public void initialize(Email constraintAnnotation) {
        this.regexp = constraintAnnotation.regexp();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(value==null){return true;}
        if( value.matches(regexp)){
            return true;
        }
        return false;
    }

}

这里只要实现ConstraintValidator<Email, String>接口就创建了一个验证器。initialize方法得到注解的regexp值,在isValid方法中进行验证,符合正则表达式就返回true,否则返回false。

需要注意的是,当value为空,也就是验证的对象没有初始化的时候,要编写相应的验证规则,不然会报错的。在上面代码中编写的是:

if(value==null){return true;}

也即是,当验证对象为空时,返回成功。

第三步是编写默认错误信息。其实这一步在第一步已经做了,通过default,所以这步不用做。


1、hibernate validation的文档说得更详细:
Creating a simple constraint.html

2、这篇博客及其下一篇讲得也挺好:
深入理解Java:注解(Annotation)自定义注解入门

3、常见错误:
HV000030: No validator could be found for type
原因一般是没有设置@Constraint(validatedBy = { EmailValidator.class })

HV000028: Unexpected exception during isValid call
原因一般是没有设置

if(value==null){return true;}

4、JSR文献:
JSR 303: Bean Validation

猜你喜欢

转载自sjmz30071360.iteye.com/blog/2372410