Spring Boot 2.3 以上参数校验无效解决方法(表单验证)

2021-04-14 15:19:43
Spring Boot 2.3 版本将不再内部依赖 validator,我们在pom文件中添加如下依赖 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> ``` 控制器中使用`@Valid`注解 ```java import javax.validation.Valid; @RestController() public class ProductController { @PostMapping("/api/product/create") public void create(@Valid @RequestBody ProductCreateDto product) { productMapper.insert(product); } } ``` 编写验证规则 ```java import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class ProductCreateDto { @NotBlank(message = "产品名称不能为空") private String name; @NotNull private String content; } ``` 官方更新日志如下 ![v.png](https://static.daimaku.net/post/202104/14/41570974f81c4a0de14ab598f4463ffb.png)