关于java:@Valid与@Validated在Spring中的用法

Usage of @Valid vs @Validated in Spring

由于这个问题,我想我了解验证的工作方式。

对于JPA,这里有一个称为JSR-303的规范,解释了Bean验证应如何工作,然后我们使用的实现也包括常用的Hibernate Validator或Apache BVal。

我正在努力在代码的某些部分中使用@Valid。我没有使用@Validated,因为我不需要组验证。

您可以在此处找到演示项目的示例

PropertyExample类中,您可以看到我标记了我的类以进行bean验证。

使用@Validated时,一切都按预期进行,因为我违反了application.yml文件中的约束。
@Validated上使用@Valid时,似乎没有任何反应。我不理解为什么。

我也看到这些注释可以在ElementType.PARAMETER上使用,但是当我在构造函数初始化期间使用它们时,验证似乎也不会触发。

我们将非常感谢您对如何使用这些注释(尤其是@Valid)进行说明。


它仅在使用Validated时有效,而在使用Valid时无效,这仅是因为Spring Boot要求对属性类进行验证才能对其进行注释。 请参阅文档:

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

[...]

You can also trigger validation by annotating the @Bean method that creates the configuration properties with @Validated.

请注意,由于Valid注释不适用于类,因此它们可能不允许在属性类上使用Valid。