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

问题描述

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

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,@验证的是 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's Valid的变种,支持验证规范组.专为方便使用 Spring 的 JSR-303 支持而设计,但不是 JSR-303 特定的.

这没有多大帮助,因为它并不能准确说明它的不同之处.如果有的话.两者对我来说似乎都很好.

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.

转到this jira ticket以了解注释是如何产生的.

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

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

08-21 03:02