Using Java EE 6 Bean Validation

丶灬走出姿态 提交于 2019-11-28 00:30:53

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. If it were an @Entity it would be your JPA provider which triggers validation, in your case you need to do it yourself.

There's a nice documentation for Hibernate Validator which is the reference implementation for JSR-303.

Example

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

Using Car and validating:

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.).

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; this happens transparently e.g. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!