简体   繁体   English

使用Java EE 6 Bean验证

[英]Using Java EE 6 Bean Validation

I am trying to use Java EE 6 Validation as specified here 我正在尝试使用此处指定的Java EE 6验证

http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html

I have annotated a simple field 我注释了一个简单的字段

@Max(11)
@Min(3)
private int numAllowed;

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. 我的约束检查尚未启动。我希望它能在调用该字段的setter方法时起作用。 The only import in my class is 我班上唯一的进口是

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

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? 我将约束放在简单POJO而不是@Entity类中的文件上,这样可以吗?

Your use of the annotations is just fine. 您对注释的使用就很好。 There's a validator implementation for each of those rest assured. 每个放心的人都有一个验证器实现。

However, at some point you need to trigger the validation of this POJO. 但是,有时需要触发此POJO的验证。 If it were an @Entity it would be your JPA provider which triggers validation, in your case you need to do it yourself. 如果它是@Entity则它将是触发验证的JPA提供程序,在这种情况下,您需要自己进行验证。

There's a nice documentation for Hibernate Validator which is the reference implementation for JSR-303. Hibernate Validator有一个不错的文档,它是JSR-303的参考实现。

Example

public class Car {
    @NotNull
    @Valid
    private List<Person> passengers = new ArrayList<Person>();
}

Using Car and validating: 使用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() );

You may also want to read how bean validation is integrated with other frameworks (JPA, CDI, etc.). 您可能还想阅读Bean验证如何与其他框架 (JPA,CDI等) 集成

Just putting a constraint annotation to a field will not cause its evaluation. 仅将约束注释添加到字段将不会导致对其求值。 Instead some mechanism must trigger validation via the javax.validation.Validator API; 相反,某些机制必须通过javax.validation.Validator API触发验证。 this happens transparently eg for JPA entities, properties bound to JSF input elements or constrained methods of CDI beans in Java EE 7. If you want to validate an un-managed POJO, you have to invoke the validator yourself. 例如,对于JPA实体,绑定到JSF输入元素的属性或Java EE 7中CDI bean的受约束方法,这种情况是透明发生的。如果要验证非托管POJO,则必须自己调用验证器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM