Java Bean Validation
JSR是Java Specification Requests
的缩写,意思是Java 规范提案。关于数据校验这块,最新的是JSR380
,也就是我们常说的Bean Validation 2.0
。
Bean Validation 2.0 是JSR第380号标准。该标准连接如下:https://www.jcp.org/en/egc/view?id=380
Bean Validation的主页:http://beanvalidation.org
Bean Validation的参考实现:https://github.com/hibernate/hibernate-validatorBean Validation 2.0 是JSR第380号标准。该标准连接如下:https://www.jcp.org/en/egc/view?id=380
Bean Validation的主页:http://beanvalidation.org
Bean Validation的参考实现:https://github.com/hibernate/hibernate-validator
Bean Validation
是一个通过配置注解来验证参数的框架,它包含两部分Bean Validation API
(规范)和Hibernate Validator
(实现)。
Bean Validation
是Java定义的一套基于注解/xml的数据校验规范,目前已经从JSR 303
的1.0版本升级到JSR 349
的1.1版本,再到JSR 380
的2.0版本(2.0完成于2017.08).
兼容性表格
Bean Validation | Hibernate Validation | JDK | Spring Boot |
---|---|---|---|
1.1 | 5.4 + | 6+ | 1.5.x |
2.0 | 6.0 + | 8+ | 2.0.x |
关于Bean Validation 2.0的关注点(新特性)
- 对Java的最低版本要求是Java 8
- 支持容器的校验,通过TYPE_USE类型的注解实现对容器内容的约束:
List<@Email String>
- 支持日期/时间的校验,
@Past
和@Future
- 拓展元数据(新增注解):
@Email,@NotEmpty,@NotBlank,@Positive, @PositiveOrZero,@Negative,@NegativeOrZero,@PastOrPresent和@FutureOrPresent
- 像
@Email、@NotEmpty、@NotBlank
之前是Hibernate额外提供的,2.0标准后hibernate自动退位让贤并且标注为过期了 Bean Validation 2.0
的唯一实现为Hibernate Validator
。(其实还有Apache BVal
,但是你懂的,forget it)- 对于
Hibernate Validator
,它自己也扩展了一些注解支持。 - 6.0以上版本新增(对应标准2.0版本):
@UniqueElements、@ISBN、@CodePointLength
- 6.0以下版本可以使用的:
@URL、@ScriptAssert、@SafeHtml、@Range、@ParameterScriptAssert、@Mod11Check、@Mod10Check、@LuhnCheck、@Length、@EAN、@Currency、@CreditCardNumber、@ConstraintComposition、
Hibernate Validator
默认会校验完所有的属性,然后返回所有的验证失败信息
。开启fail fast mode后,只要有一个验证失败,则返回验证失败信息。
注意:本文归作者所有,未经作者允许,不得转载