
我想在执行如下方法之前使用@Validated(group = Foo.class)注释来验证参数:
public void doFoo(Foo @Validated(groups=Foo.class) foo){}
当我将此方法放在我的Spring应用程序的Controller中时,执行@Validated并在Foo对象无效时抛出错误.但是,如果我在应用程序的Service层中的方法中放置相同的东西,则不执行验证,即使Foo对象无效,该方法也会运行.
你不能在服务层使用@Validated注释吗?或者我是否必须配置额外的东西以使其工作?
更新:
我在service.xml中添加了以下两个bean:
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>
并用@Null替换@Validate,如下所示:
public void doFoo(Foo @Null(groups=Foo.class) foo){}
我知道这是一个非常愚蠢的注释,但我想检查一下,如果我现在调用该方法并传递null,它将抛出违规异常.那么为什么它执行@Null注释而不是@Validate注释呢?我知道一个是来自javax.validation而另一个来自Spring,但我不认为这与它有什么关系?
我们称之为服务层,它只是一个普通的bean,没有从MVC(DispatcherServlet)堆栈中添加任何额外的行为.因此,您不能指望Spring的任何验证.你需要自己动手,可能是AOP.
使用MethodValidationPostProcessor,查看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.
@Validated注释仅用于指定验证组,它本身不会强制进行任何验证.您需要使用其中一个javax.validation注释,如@Null或@Valid.请记住,您可以在方法参数上使用任意数量的注释.
转载注明原文:java – Spring @Validated在服务层 - 乐贴网