使用 Java EE 6 Bean 验证 [英] Using Java EE 6 Bean Validation
问题描述
我正在尝试使用此处指定的 Java EE 6 验证
I am trying to use Java EE 6 Validation as specified here
http://docs.oracle.com/javaee/6/教程/doc/gircz.html
我已经注释了一个简单的字段
I have annotated a simple field
@Max(11)
@Min(3)
private int numAllowed;
文档说对于内置约束,默认实现可用"但我如何指定它.我的约束检查没有开始.我希望它能够调用该字段的 setter 方法.我班上唯一的导入是
The docs says "For a built-in constraint, a default implementation is available" but how do I specify this. My constraints checks are not kicking in. I would expect it to work on calling of the setter method for the field. The only import in my class is
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
我如何/在哪里指定实现?我将约束放在一个简单的 POJO 中,而不是 @Entity 类中,这样可以吗?
How/where do I specify the implementation? I am putting the constraint on a filed in a simple POJO not an @Entity class, is this ok?
推荐答案
您对注释的使用很好.每个放心的人都有一个验证器实现.
Your use of the annotations is just fine. There's a validator implementation for each of those rest assured.
但是,在某些时候您需要触发此 POJO 的验证.如果它是一个 @Entity
,它将是您的 JPA 提供程序触发验证,在您的情况下,您需要自己做.
However, at some point you need to trigger the validation of this POJO. If it were an @Entity
it would be your JPA provider which triggers validation, in your case you need to do it yourself.
有一个 很好的 Hibernate Validator 文档,它是 JSR-303 的参考实现.
There's a nice documentation for Hibernate Validator which is the reference implementation for JSR-303.
示例
public class Car {
@NotNull
@Valid
private List<Person> passengers = new ArrayList<Person>();
}
使用Car
并验证:
Car car = new Car( null, true );
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );
您可能还想阅读 bean 验证如何与其他框架集成(JPA、CDI 等).
You may also want to read how bean validation is integrated with other frameworks (JPA, CDI, etc.).
这篇关于使用 Java EE 6 Bean 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!