java - 服务层中的Spring @Validated

标签 java spring validation spring-mvc

嘿嘿,

我想在执行如下方法之前使用 @Validated(group=Foo.class) 注释来验证参数:

public void doFoo(Foo @Validated(groups=Foo.class) foo){}

当我将此方法放在我的 Spring 应用程序的 Controller 中时,@Validated 被执行并在 Foo 对象无效时引发错误。但是,如果我在应用程序的 Service 层中的方法中放入相同的内容,则不会执行验证,并且即使 Foo 对象无效,该方法也会运行。

不能在服务层使用@Validated注解吗?还是我必须做一些额外的配置才能让它工作?

更新:

我已将以下两个 bean 添加到我的 service.xml:

<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>

并将 @Validate 替换为 @Null,如下所示:

public void doFoo(Foo @Null(groups=Foo.class) foo){}

我知道这是一个非常愚蠢的注释,但我想检查如果我现在调用该方法并传递 null,它会抛出一个违规异常。那么为什么它执行 @Null 注释而不是 @Validate 注释呢?我知道一个来自 javax.validation 而另一个来自 Spring 但我认为这与它无关?

最佳答案

在 Spring MVC 堆栈的眼中,没有服务层这样的东西。它适用于 @Controller 类处理程序方法的原因是 Spring 使用称为 ModelAttributeMethodProcessor 的特殊 HandlerMethodArgumentResolver 在解析要使用的参数之前执行验证你的处理方法。

我们称之为服务层只是一个普通的 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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19425221/

相关文章:

java - 一般 SOAP Web 服务问题

java - 如何延迟Java代码直到另一部分代码完成?

java - NumberUtils 在将 BigDecimal 转换为 Long 时抛出异常,但在转换为 Integer 时成功

java - Spring 3 宠物诊所示例使用 ${owner.new},在 JSTL EL 中,我在哪里可以阅读有关 .new 运算符的信息?

java - 默认情况下不验证扩展默认值的验证组

java - 获得错误的底部导航 fragment onclick

java - 最新文件和文件的动态命名

java - Spring beans 的键为 Map<String,Foo>

javascript - Angularjs 使用表达式进行验证

javascript - URI 正则表达式 : Replace http://, https ://, ftp://如果 URL 有效则为空字符串