Spring Boot Rest API @RequestBody 中的@Valid 与@Validated [英] @Valid vs @Validated in Spring Boot Rest API @RequestBody

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

问题描述

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

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

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

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?

@Validated @RequestBody

@Valid @RequestBody

推荐答案

两者一般没有太大区别,@Valid 来自 JSR-303 标准,@Validated 是弹簧标准.根据spring文档:

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

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

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.

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

但是有区别,其中之一是例如,如果您需要在验证注释中使用group,则需要使用@Validated,它不受支持使用 @Valid.

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

这篇关于Spring Boot Rest API @RequestBody 中的@Valid 与@Validated的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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