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

SpringBoot中@Validated未校验ItemDTO字段,如何触发嵌套校验?

解决SpringBoot 2.1.9.RELEASE中嵌套DTO分组校验不生效的问题

要让ItemLimitDTO内部的ItemDTO字段校验正常工作,需要从触发嵌套校验和关联校验分组两个关键维度调整:

具体调整步骤

  • 在ItemLimitDTO的嵌套ItemDTO字段上添加@Valid注解:Spring不会自动递归校验嵌套对象,必须通过该注解明确触发对内部ItemDTO的校验逻辑。
  • 给ItemDTO中的所有校验注解指定对应的New.class分组:因为外层使用了@Validated(New.class),只有标注了该分组的校验规则才会被触发执行。

示例代码

调整后的ItemLimitDTO

public class ItemLimitDTO {
    @NotNull(groups = New.class)
    @Valid // 触发嵌套ItemDTO的校验
    private ItemDTO item;

    // 其他字段、getter/setter
}

调整后的ItemDTO

public class ItemDTO {
    @NotBlank(groups = New.class) // 关联New分组
    private String itemName;

    @Min(value = 1, groups = New.class) // 关联New分组
    private Integer quantity;

    // getter/setter
}

控制器层写法

@RestController
public class ItemController {
    @PostMapping("/create")
    public ResponseEntity<Void> createItem(@Validated(New.class) @RequestBody ItemLimitDTO dto) {
        // 业务逻辑处理
        return ResponseEntity.ok().build();
    }
}

原理说明

  1. @Valid的作用是告知Spring校验器递归校验当前字段对应的嵌套对象,没有该注解时,Spring只会校验ItemLimitDTO本身的字段,忽略内部ItemDTO的规则。
  2. 分组校验机制下,只有校验注解(如@NotBlank、@Min)指定了与@Validated一致的分组(New.class),这些规则才会在本次校验中被执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:42:10