I want to use Spring 3 for validation.
In the reference documentation, section 6.2 deals with the Validator interface that we may implement for the classes we want to validate. It’s explained how to create the Validator class but not how to validate objects.
Section 6.7 deals with the use of JSR-303 API and the annotations that come with. It seems that it’s a different way to validate objects (in this case, using annotations without creating Validator classes).
Are there really two ways to use Spring validation or I’m missing something?
One simple question, it’s also specified that an implementation of JSR-303 API must be present on the classpath. One proposed implementation is Hibernate-Validator. Does Spring provide an implementation?
Thanks
Yes, there are two ways:
I would recommend to use JSR 303. – In my opinion there is only one reason to use the old validators: that is if you need a LOT of cross field validations, because they are relative hard to implement with JSR 303 (but its is possible)
To use JSR 303 you need to add an validator implementation, for example Hibernate-Validator (it is the default implementation of JSR 303) (Hibernate-Validator is NOT the Hibernate ORM!, it is only related)
This is a bit like JPA, there is the common neutral specification (javax.jpa/javax.validation) and the different provider implementations (for JPA for example: EclipseLink or Hibernate)
This is an example how to test a validation (the goal of the test was to test the validation itself, but I changed the Validator to a common one), anyway it should show you how to test a validator:
But in an Spring MVC Controller it is much easier, you only need to add
@Validto your command object parameter and need to add aBindingResultparameter directly after the command object parameterAnd the UserCreateCommand is just a POJO where the fields are annotated with a lot of JSR303 Validation constraints.