In the eyes of a Spring MVC stack, there is no such thing as a service layer. The reason it works for @Controller
class handler methods is that Spring uses a special HandlerMethodArgumentResolver
called ModelAttributeMethodProcessor
which performs validation before resolving the argument to use in your handler method.
The service layer, as we call it, is just a plain bean with no additional behavior added to it from the MVC (DispatcherServlet
) stack. As such you cannot expect any validation from Spring. You need to roll your own, probably with AOP.
With MethodValidationPostProcessor
, take a look at the javadoc
Applicable methods have JSR-303 constraint annotations on their
parameters and/or on their return value (in the latter case specified
at the method level, typically as inline annotation).Validation groups can be specified through Spring’s Validated
annotation at the type level of the containing target class, applying
to all public service methods of that class. By default, JSR-303 will
validate against its default group only.
The @Validated
annotation is only used to specify a validation group, it doesn’t itself force any validation. You need to use one of the javax.validation
annotations like @Null
or @Valid
. Remember that you can use as many annotations as you would like on a method parameter.