In this post I will share a sample application I used to see in action the following Bean Validation 2.0 features:
- List items validation
- Temporal validation using Java 8
Project setup
Hibernate Validator is the RI for Bean Validation 2.0 and the project, being a maven or gradle project, must use the following dependencies (or later versions): org.hibernate:hibernate-validator:6.0.2.Final and you should also add org.glassfish:javax.el:3.0.1-X as a hibernate validator dependency, where X is the build, check the maven repository for more. This is what my pom.xml looks like:
Using bean validation annotations in a bean fields
To test the new annotations I used the following bean:
Notice the new annotations in subscribers and in manufactureDate and expirationDate fields:
- subscribers: I am validating users emails, all the Strings added to this list should be an email. To do this a simple @Email annotation solved the problem;
- manufactureDate: The validation is to make sure that the manufactureDate is a past date and to do so a single @Past annotation will make sure that this is correctly validated;
- expirationDate: The product should expire in future and the @Future annotation solves everything.
Finally I can test this in a main class, see:
When running this only p4 will be valid:
The code is in my github. Feel free to clone it and make more tests on top of this project.
Nenhum comentário:
Postar um comentário