用Annotations 给类或者类的属性加上约束(constraint),在运行期检查属性值是很优雅的.Hibernate Validator就是这样的一个框架.该框架是十分容易的(就像参考文档中宣称的那样),几乎没有什么学习曲线,Validator 是一个验证框架不需要和Hibernate的其他部分绑定就可以使用,只要在你的项目中添加Hibernate-annotations.jar库就可以了.
As announced earlier, the highlight of the 4.2 release is the implementation of method level constraints (HV-347) as described in Appendix C of the Bean Validation specification. Many thanks to Gunnar for implementing this new feature. Method level validation allows to apply constraints to method ">parameters or return values like this:
public @NotNull String saveItem(@Valid @NotNull Item item, @Max(23) BigDecimal price)
To validate these constraints you would get hold of a MethodValidator via the Validator.unwrap() method:
MethodValidator validator = Validation.byProvider( HibernateValidator.class )
.configure()
.buildValidatorFactory()
.getValidator()
.unwrap( MethodValidator.class );
and use one of the following methods of this new interface:
public interface MethodValidator {
public <T> Set<MethodConstraintViolation<T>> validateParameter(T object, Method method, Object parameterValue, int parameterIndex, Class<?>... groups);
public <T> Set<MethodConstraintViolation<T>> validateParameters(T object, Method method, Object[] parameterValues, Class<?>... groups);
public <T> Set<MethodConstraintViolation<T>> validateReturnValue(T object, Method method, Object returnValue, Class<?>... groups);
}
The returned MethodConstraintViolation is derived from ConstraintViolation and provides additional method level validation specific information. For example it can contain the method name and index of the parameter which caused the constraint violation. The documentation for this feature is still work in progress and will be completed in the following releases.