Spring中@Valid和@Validated之间的区别 [英] Difference between @Valid and @Validated in Spring

查看:214
本文介绍了Spring中@Valid和@Validated之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring支持两种不同的验证方法:Spring验证和JSR-303 bean验证。两者都可以通过定义一个Spring验证器来使用,该验证器委托给其他委托者,包括bean验证器。到目前为止一切顺利。

Spring supports two different validation methods: Spring validation and JSR-303 bean validation. Both can be used by defining a Spring validator that delegates to other delegators including the bean validator. So far so good.

但是当注释实际请求验证的方法时,这是另一个故事。我可以像这样注释

But when annotating methods to actually request validation, it's another story. I can annotate like this

@RequestMapping(value = "/object", method = RequestMethod.POST)
public @ResponseBody TestObject create(@Valid @RequestBody TestObject obj, BindingResult result) {

或者像这样

@RequestMapping(value = "/object", method = RequestMethod.POST)
public @ResponseBody TestObject create(@Validated @RequestBody TestObject obj, BindingResult result) {

这里,@ Valid是javax.validation.Valid ,@ Validated是 org.springframework.validation.annotation.Validated 。后者的文档说

Here, @Valid is javax.validation.Valid, and @Validated is org.springframework.validation.annotation.Validated. The docs for the latter say


JSR-303的变体有效,支持验证
组的规范。设计方便使用Spring的JSR-303支持,但
不是特定于JSR-303。

Variant of JSR-303's Valid, supporting the specification of validation groups. Designed for convenient use with Spring's JSR-303 support but not JSR-303 specific.

这对我们来说无济于事因为它并没有确切地说明它是如何不同的。如果有的话。两者似乎都对我很好。

which doesn't help much because it doesn't tell exactly how it's different. If at all. Both seem to be working pretty fine for me.

推荐答案

正如你从文档中引用的那样, @Validated添加了以支持验证组,即验证bean中的字段组。这可以在多步骤表单中使用,您可以在第一步中验证名称,电子邮件等,然后在后续步骤中验证其他字段。

As you quoted from the documentation, @Validated was added to support "validation groups", i.e. group of fields in the validated bean. This can be used in multi step forms where you may validate name, email, etc.. in first step and then other fields in following step(s).

原因为什么没有添加到 @Valid 注释是因为它是使用java社区进程(JSR-303)标准化的,这需要时间并且Spring开发人员希望允许人们更快地使用此功能。

The reason why this wasn't added into @Valid annotation is because that it is standardized using the java community process (JSR-303), which takes time and Spring developers wanted to allow people to use this functionality sooner.

转到此jira ticket 看看注释是如何形成的。

Go to this jira ticket to see how the annotation came into existence.

这篇关于Spring中@Valid和@Validated之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆