如何自定义hibernate validation注解示例代码

时间:2021-05-02

bean validation 中内置的 constraint

@null 被注释的元素必须为 null
@notnull 被注释的元素必须不为 null
@asserttrue 被注释的元素必须为 true
@assertfalse 被注释的元素必须为 false
@min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@decimalmin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@decimalmax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@size(max=, min=) 被注释的元素的大小必须在指定的范围内
@digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@past 被注释的元素必须是一个过去的日期
@future 被注释的元素必须是一个将来的日期
@pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式

hibernate validator 附加的 constraint
@notblank(message =) 验证字符串非null,且长度必须大于0
@email 被注释的元素必须是电子邮箱地址
@length(min=,max=) 被注释的字符串的大小必须在指定的范围内
@notempty 被注释的字符串的必须非空
@range(min=,max=,message=) 被注释的元素必须在合适的范围内

效果和优点

先看最后效果:

? 1 2 3 4 5 6 public class userentity { @password private string password; @email private string email; }

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

? 1 2 @pattern(regexp="...") private string email;

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

实现

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

? 1 2 3 4 5 6 7 <!-- 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)

第一步,创建注解:

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @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 }),这里指定注解的验证类,根据实际替换类名。

第二步,创建验证类:

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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为空,也就是验证的对象没有初始化的时候,要编写相应的验证规则,不然会报错的。在上面代码中编写的是:

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

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

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

原文链接:https://blog.csdn.net/ruangong1203/article/details/51002360

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章