What does the @Valid annotation indicate in Spring?
@Valid
in itself has nothing to do with Spring. It's part of Bean Validation specification(there are several of them, the latest one being JSR 380 as of second half of 2017), but @Valid
is very old and derives all the way from JSR 303.
As we all know, Spring is very good at providing integration with all different JSRs and java libraries in general(think of JPA, JTA, Caching, etc.) and of course those guys took care of validation as well. One of the key components that facilitates this is MethodValidationPostProcessor.
Trying to answer your question - @Valid
is very handy for so called validation cascading when you want to validate a complex graph and not just a top-level elements of an object. Every time you want to go deeper, you have to use @Valid
. That's what JSR dictates. Spring will comply with that with some minor deviations(for example I tried putting @Validated
instead of @Valid
on RestController method and validation works, but the same will not apply for a regular "service" beans).
Adding to above answers, take a look at following. AppointmentForm
's date
column is annotated with couple of annotations. By having @Valid
annotation that triggers validations on the AppointmentForm
(in this case @NotNull
and @Future
). These annotations could come from different JSR-303 providers (e.g, Hibernate, Spring..etc).
@RequestMapping(value = "/appointments", method = RequestMethod.POST)
public String add(@Valid AppointmentForm form, BindingResult result) {
....
}
static class AppointmentForm {
@NotNull @Future
private Date date;
}
It's for validation purposes.
Validation It is common to validate a model after binding user input to it. Spring 3 provides support for declarative validation with JSR-303. This support is enabled automatically if a JSR-303 provider, such as Hibernate Validator, is present on your classpath. When enabled, you can trigger validation simply by annotating a Controller method parameter with the @Valid annotation: After binding incoming POST parameters, the AppointmentForm will be validated; in this case, to verify the date field value is not null and occurs in the future.
Look here for more info:
http://blog.springsource.com/2009/11/17/spring-3-type-conversion-and-validation/