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

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

1. 基本使用

1.1 添加依赖

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

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

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

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 注解触发校验:

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 定义分组接口

创建分组接口:

public interface GroupA {}
public interface GroupB {}
2.2 在实体类中指定分组

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

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 指定分组:

@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

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 捕获并处理。

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个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知识浅谈

您的支持将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值