Spring中@Valid与@Validated的用法 [英] Usage of @Valid vs @Validated in Spring

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

问题描述

由于这个问题,我想我知道验证的方式正在工作.

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 @Validin 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:

每当使用Spring的@Validated批注进行批注时,Spring Boot就会尝试验证@ConfigurationProperties类

Spring Boot attempts to validate @ConfigurationProperties classes whenever they are annotated with Spring’s @Validated annotation

[...]

您还可以通过使用@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的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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