Spring @Validated in service layer

后端 未结 5 469
天命终不由人
天命终不由人 2020-12-01 05:26

Hej,

I want to use the @Validated(group=Foo.class) annotation to validate an argument before executing a method like following:

public v         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 06:15

    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.

提交回复
热议问题