Spring Boot Rest API @RequestBody 中的@Valid 与@Validated

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44051244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:25:18  来源:igfitidea点击:

@Valid vs @Validated in Spring Boot Rest API @RequestBody

springspring-boot

提问by alltej

I am coming from a .NET background in developing REST APIs. Now working on java REST project using spring boot.

我来自开发 REST API 的 .NET 背景。现在使用 spring boot 处理 java REST 项目。

First my validation at the controller @RequestBody just stop working. While trying to fix it, I saw different ways to implement. So what would be the correct way to annotate the @RequestBody?

首先,我在控制器 @RequestBody 上的验证就停止工作了。在尝试修复它时,我看到了不同的实现方式。那么注释@RequestBody 的正确方法是什么?

@Validated @RequestBody

or

或者

@Valid @RequestBody

回答by Jaiwo99

There are generally no huge difference between them two, @Validis from JSR-303 standand, @Validatedis spring standard. according to spring document:

两者一般没有太大区别,@Valid都是来自JSR-303标准,@Validated是spring标准。根据spring文件:

Spring provides a Validator interface that can be used for validation in all layers of an application. In Spring MVC you can configure it for use as a global Validator instance, to be used whenever an @Valid or @Validated controller method argument is encountered, and/or as a local Validator within a controller through an @InitBinder method. Global and local validator instances can be combined to provide composite validation.

Spring 提供了一个 Validator 接口,可用于在应用程序的所有层中进行验证。在 Spring MVC 中,您可以将其配置为全局 Validator 实例,在遇到 @Valid 或 @Validated 控制器方法参数时使用,和/或通过 @InitBinder 方法作为控制器内的本地验证器。可以组合全局和本地验证器实例以提供复合验证。

Reference: https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-validation

参考:https: //docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-validation

However there are differences, one of them is for example, if you need use groupin your validation annotation, you need to use @Validated, it is not supported with @Valid.

但是存在差异,其中之一是例如,如果您需要group在验证注释中使用@Validated,则需要使用,而@Valid.

回答by Matthias

@Valid is in the JSR-Specification and @Validated is from spring framework.

@Valid 在 JSR 规范中,@Validated 来自 spring 框架。

When your program should be compatible to EJB/JSR Standard use @Valid otherwise you can use both.

当您的程序应该与 EJB/JSR 标准兼容时,请使用 @Valid 否则您可以同时使用两者。