场景:
Controller类接口,需要提前校验传递的参数的正确性,通常我们会加上注解 @Validated @Valid来校验参数,比如校验非空、数据格式等,例如:
校验的实体:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | @Data public class TestValidVO { private String id; @NotBlank(message = "姓名不能为空") private String name; @Size(min = 7,max = 11,message = "电话号码格式不正确") private String phone; @NotBlank @Email(message = "邮箱格式不正确") private String email; @DecimalMin(value = "0",message = "年龄不能小于0岁") @DecimalMax(value = "150",message = "年龄不能大于150岁") @NotNull(message = "年龄不能为空") private Integer age; } |
controller接口校验:
1 2 3 4 5 | @PostMapping(value = "/testPostValid") public BaseResponse testPostValidException(@RequestBody @Validated TestValidVO vo) { List<User> u = userMapper.selectAll(); return BaseResponse.ok(u); } |
问题:
入参邮件格式错误,postman调用接口 testPostValid,没有出现异常的结果

解决:
将springboot的版本降低到2.3.0以下;或者加入依赖 spring-boot-starter-validation;
建议加入 spring-boot-starter-validation 依赖,这样不会改变springboot的版本,从而不影响项目的其他业务功能。
1 2 3 4 | <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> |
解决效果:
