You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@Valid注解校验Spring Boot @RequestBody嵌套对象不生效问题

问题原因
  • @Valid注解的触发规则是仅对非null的嵌套对象执行内部字段校验,你当前Student类的subject字段未添加非空校验规则,当请求不传递任何Subject相关参数时,subject字段会被序列化为null,此时嵌套校验逻辑自然不会执行,所以不会抛出异常。
  • 额外排查点:Spring Boot 2.3及更高版本默认不集成校验依赖,若未手动引入spring-boot-starter-validation也可能导致所有校验规则不生效。
解决方案

1. 给嵌套对象字段添加非空校验

在Student类的subject字段上添加@NotNull注解,明确要求该字段不可为null,修改后的代码如下:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
  @NotEmpty(message = "First Name field can not be null or empty")
  @NotBlank(message = "First Name field can not be blank")
  private String firstName;
  @NotEmpty(message = "Last Name field can not be null or empty")
  @NotBlank(message = "Last Name field can not be blank")
  private String lastName;
  // 新增@NotNull注解
  @NotNull(message = "Subject字段不能为null")
  @Valid
  private Subject subject;      
}

修改后两种场景都会触发校验:

  • 请求不传Subject相关参数:触发@NotNull校验抛出异常
  • 请求传了Subject但topic为空/空白:触发Subject类内部的字段校验抛出异常

2. 确认校验依赖已引入

如果所有校验规则都不生效,检查项目依赖是否已添加校验启动器:

Maven配置(pom.xml)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Gradle配置(build.gradle)

implementation 'org.springframework.boot:spring-boot-starter-validation'

内容的提问来源于stack exchange,提问作者sawsb123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:09:03