一文读懂Spring中的@Validated注解

发布于:2024-05-01 ⋅ 阅读:(26) ⋅ 点赞:(0)

1. 基本知识

在Spring框架中,@Validated注解用于在方法参数级别上开启方法参数校验的功能

在方法参数上使用JSR-303/JSR-380规范中定义的校验注解,如@NotNull@NotBlank@Size等,以对方法参数进行约束

@Valid注解有所不同,@Valid注解通常用于在Bean级别上进行校验,而@Validated注解则用于在方法参数级别上进行校验

对于Java的相关知识推荐阅读:java框架 零基础从入门到精通的学习路线 附开源项目面经等(超全)

  • 作用范围:用于方法的参数上,表示对该参数进行校验
  • Spring版本:在Spring 3.1版本中引入的,用于支持方法参数的校验功能
  • 校验失败处理:校验失败时,Spring会抛出MethodArgumentNotValidException异常
    Controller中通过@ExceptionHandler方法来捕获这个异常,并进行自定义的错误处理或返回错误信息给客户端
  • 参数校验的开启与配置:在Spring配置文件中添加<mvc:annotation-driven/>或者在Spring Boot应用中添加spring-boot-starter-validation依赖来启用

示例Demo:

import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.NotBlank;

@Service
@Validated
public class MyService {

    public void process(@NotBlank(message = "Name must not be blank") String name) {
        // 方法体
    }
}

2. @validated和@valid差异

特性 @Validated @Valid
作用对象 方法参数 Bean对象
校验失败处理 抛出MethodArgumentNotValidException异常 通常在Controller层的方法参数上使用,通过BindingResult参数捕获校验错误
适用场景 对方法参数进行校验 对请求体中的对象进行校验
引入版本 Spring 3.1版本引入 Spring 3.0版本开始对其提供支持

示例Demo如下:

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;

@RestController
@Validated
public class MyController {

    @PostMapping("/process")
    public ResponseEntity<String> process(@Valid @RequestBody RequestDTO requestDTO) {
        // 处理请求逻辑
        return ResponseEntity.ok("Processed successfully");
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到