问题描述
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是,@ Validated是。后者的文档说
Here, @Valid is javax.validation.Valid, and @Validated is org.springframework.validation.annotation.Validated. The docs for the latter say
这对我们来说无济于事因为它并没有确切地说明它是如何不同的。如果有的话。两者似乎都对我很好。
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.
转到看看注释是如何形成的。
Go to this jira ticket to see how the annotation came into existence.
这篇关于Spring中@Valid和@Validated之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!