Spring 中 @Validated 嵌套校验问题

205次阅读
没有评论

共计 758 个字符,预计需要花费 2 分钟才能阅读完成。

当使用 @Validated 进行参数校验时,如果方法参数是一个包含嵌套对象的复杂对象,@Validated 只会对顶层对象进行校验,而不会递归地对嵌套对象进行校验。例如:

public class Parent {
    @NotNull(message ="parent name 不能为空")
    private String name;

    @NotNull
    private Child child;
}

public class Child {
    @NotNull(message ="child name 不能为空")
    private String name;
}

@RestController
public class MyController {

    @PostMapping("/test")
    public void test(@Validated @RequestBody Parent parent) {
        // some logic
    }
}

此时传递如下参数依旧可以通过校验,并不会提示 child name 不能为空

{
    "name": "parent",
    "child": {

    }
}

如果需要嵌套校验,需要在 child 字段上设置 @Valid 注解,即:

public class Parent {
    @NotNull(message ="parent name 不能为空")
    private String name;

    @Valid
    private Child child;
}

public class Child {
    @NotNull(message ="child name 不能为空")
    private String name;
}

@RestController
public class MyController {

    @PostMapping("/test")
    public void test(@Validated @RequestBody Parent parent) {
        // some logic
    }
}
AD:【腾讯云服务器大降价】2核4G 222元/3年 1核2G 38元/年
正文完
 
阿蛮君
版权声明:本站原创文章,由 阿蛮君 2024-09-03发表,共计758字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
Copyright © 2022-2024 阿蛮君博客 湘ICP备2023001393号
本网站由 亿信互联 提供云计算服务 | 蓝易云CDN 提供安全防护和加速服务
Powered by Wordpress  Theme by Puock