问题描述
由于这个问题,我想我知道验证的方式正在工作.
Thanks to this question, I think I understand how validation is working.
对于JPA,这里有一个称为JSR-303的规范,解释了Bean验证应如何工作,然后我们使用的是诸如常用的Hibernate Validator或Apache BVal之类的实现.
As for JPA, here we have a specification called JSR-303 explaining how Bean Validation should work and then we are using implementations like the commonly used Hibernate Validator or Apache BVal also.
我正在努力在代码的某些部分中使用 @Valid
.我没有使用 @Validated
,因为我不需要组验证.
I am struggling about using @Valid
in some part of my code. I am not using @Validated
because I do not need group validation.
您可以在此处找到一个示例项目的示例
You can find an example of a demo project here
在 PropertyExample
类中,您可以看到我标记了要进行bean验证的类.
In PropertyExample
class, you can see I marked my class for bean validation to happen.
使用 @Validated
时,一切正常,因为我违反了 application.yml
文件中的约束.当在 @Validated
上使用 @Valid
时,似乎什么也没发生.我不明白为什么.
When using @Validated
, everything work as expected since I am violating a constraint in my application.yml
file.When using @Valid
over @Validated
, it seems nothing happens. I do not understand why.
我也看到这些注释可以在 ElementType.PARAMETER
上使用,但是当我在构造函数初始化期间使用它们时,验证似乎也不会触发.
I saw too that those annotations could be used on ElementType.PARAMETER
but when I am using using them during constructor initialisation, validation doesn't seem to trigger either.
对如何使用这些注释(尤其是 @Valid
)进行解释将不胜感激.
Explanations on how to used those annotations (especially the @Valid
) would be greatly appreciated.
推荐答案
它在使用Validated时有效,而在使用Valid时无效,这仅仅是因为Spring Boot要求对属性类进行验证,如果您希望对其进行验证.请参见文档:
It works when using Validated and doesn't when using Valid simply because Spring Boot requires properties classes to be annotated with Validated if you want them to be validated. See the documentation:
[...]
您还可以通过使用@Validated注释创建配置属性的@Bean方法来触发验证.
You can also trigger validation by annotating the @Bean method that creates the configuration properties with @Validated.
请注意,由于Valid注释不适用于类,因此它们可能不允许在属性类上使用Valid.
Note that they can't possibly allow the use of Valid on properties classes, since the Valid annotation isn't applicable to classes.
这篇关于Spring中@Valid与@Validated的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!