SpringBoot项目中validator做参数校验不生效的问题

 

1、SpringBoot项目中Controller的validator做参数校验不生效的问题

解决:

springboot 2.3之前的集成在spring-boot-starter-web里了,所以不需要额外引入包

springboot 2.3之后需要引入 spring-boot-starter-validation

单个参数校验和Bean字段校验还是有点区别的:单个参数校验需要在参数上增加校验注解,并在类上标注@Validated

有一篇非常详细的 SpringBoot 中使用 validator 的教程,可以参考:使用Spring Validation优雅地校验参数

 

2、SpringBoot项目中controller之外使用validator做参数校验

参考:https://zhuanlan.zhihu.com/p/164752245

使用示例总结:

入参实体bean

@Data
public class Request<T> {
    @Positive //要求数字成员必须大于0
    private Long id;

    @NotNull
    private StatusEnum status;

    @Valid //嵌套类必须加这个注解才会递归校验里面的字段
    private T data;
}

@Data
public class TestParam {
    @Positive
    private Long subId;

    @NotEmpty
    private String name;
}

1)controller层使用
  • @RequestMapping("/test")
    public Result<Boolean> test(@Valid Request<TestParam> req) {
        // xxx
        return Result.success(true);
    }
  • controller层参数的注解用@Valid和@Validated都可生效,个人觉得最好还是统一用@Valid,避免后续记忆混淆出一些尴尬的问题,比如我。

2)service或其他spring管理的bean里使用

@Service
@Validated
public class TestService {
    public boolean test(Request<TestParam> req) {
        return true;
    }
}
 
posted @ 2021-07-14 17:43  飘飘雪  阅读(9232)  评论(0编辑  收藏  举报