@Validate 注解的使用-分组案例很有用

@Validated 注解在 Spring Boot 中用于方法参数校验,通常与 @Valid 注解结合使用,确保传入的参数符合指定的约束条件。它是 Spring 对 JSR-303/JSR-380(Bean Validation)规范的扩展,支持分组校验。

1. 基本使用

1.1 添加依赖

首先,确保项目中包含 spring-boot-starter-validation 依赖:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
1.2 定义实体类

在实体类中使用校验注解,如 @NotNull@Size 等:

java 复制代码
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

    @NotNull(message = "Name cannot be null")
    private String name;

    @Size(min = 1, max = 10, message = "Description must be between 1 and 10 characters")
    private String description;

    // Getters and Setters
}
1.3 在 Controller 中使用 @Validated

在 Controller 方法参数前使用 @Validated@Valid 注解触发校验:

java 复制代码
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @PostMapping
    public String createUser(@Valid @RequestBody User user) {
        return "User is valid";
    }
}

2. 分组校验

@Validated 支持分组校验,适用于不同场景下的不同校验规则。

2.1 定义分组接口

创建分组接口:

java 复制代码
public interface GroupA {}
public interface GroupB {}
2.2 在实体类中指定分组

在实体类中为校验注解指定分组:

java 复制代码
public class User {

    @NotNull(groups = GroupA.class, message = "Name cannot be null")
    private String name;

    @Size(groups = GroupB.class, min = 1, max = 10, message = "Description must be between 1 and 10 characters")
    private String description;

    // Getters and Setters
}
2.3 在 Controller 中使用分组校验

在 Controller 方法中使用 @Validated 指定分组:

java 复制代码
@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @PostMapping("/groupA")
    public String createUserGroupA(@Validated(GroupA.class) @RequestBody User user) {
        return "User is valid for GroupA";
    }

    @PostMapping("/groupB")
    public String createUserGroupB(@Validated(GroupB.class) @RequestBody User user) {
        return "User is valid for GroupB";
    }
}

3. 方法级别校验

@Validated 还可用于方法级别的参数校验。

3.1 在 Service 层使用

在 Service 层方法参数前使用 @Validated

java 复制代码
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.validation.Valid;

@Service
@Validated
public class UserService {

    public void createUser(@Valid User user) {
        // 业务逻辑
    }
}

4. 异常处理

校验失败时,Spring 会抛出 MethodArgumentNotValidExceptionConstraintViolationException,可以通过 @ControllerAdvice@ExceptionHandler 捕获并处理。

java 复制代码
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> 
            errors.put(error.getField(), error.getDefaultMessage()));
        return errors;
    }
}

总结

@Validated 在 Spring Boot 中用于参数校验,支持分组校验和方法级别校验,结合 @Valid 使用,能有效确保数据合法性,并通过异常处理机制返回友好错误信息。

相关推荐
腾渊信息科技公司10 小时前
Spring Boot对接MES实战:视觉检测数据自动同步方案
java·人工智能·spring boot·后端·计算机视觉·ai·软件需求
爱笑的源码基地11 小时前
高并发 Redis 缓存门诊HIS系统源码,含财务统计药房进销存
java·程序·门诊系统·诊所系统·云诊所源码
莫逸风14 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
z1234567898614 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
yaoxin52112315 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
做个文艺程序员15 小时前
Linux第24篇:Java应用监控体系搭建:Prometheus+Grafana可视化运维
java·grafana·prometheus
小钻风336616 小时前
Spring Boot 文件上传详解:深入理解 MultipartFile 的使用与原理
java·开发语言
其美杰布-富贵-李16 小时前
Spring Boot 工程开发全流程说明
java·spring boot·后端
前端双越老师18 小时前
如何以前端视角(非0基础)学 Java ?
java·node.js·全栈
dear_bi_MyOnly18 小时前
【SpringBoot配置文件】
java·spring boot·后端·学习·spring·java-ee·学习方法