springboot validated不生效
时间: 2023-07-03 07:25:59 浏览: 136
如果在 Spring Boot 中使用 @Validated 注解进行参数校验不生效,一般可能出现以下几种情况:
1. 没有在 Controller 类上加上 @Validated 注解,或者加上了但是没有生效。在这种情况下,需要检查是否启用了 Spring MVC 注解处理器,可以在 application.properties 文件中加上以下配置:
```
spring.mvc.validation.enabled=true
```
2. 没有在方法参数上加上校验注解,或者加上了但是没有生效。在这种情况下,需要检查是否在方法参数前面加上了 @Valid 或者 @Validated 注解。
3. 校验注解没有起作用。在这种情况下,需要检查是否引入了正确的校验依赖。在 Spring Boot 2.x 版本中,需要引入 Hibernate Validator 的依赖:
```
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.1.5.Final</version>
</dependency>
```
4. 在 application.properties 文件中配置了开启校验,但是使用了 GET 方法请求。在 Spring MVC 中,GET 方法默认不会进行校验,只有 POST 方法才会进行校验。如果需要在 GET 方法中进行校验,可以在 Controller 类上加上以下注解:
```
@RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
```
5. 在方法参数中使用了非 Spring Boot 默认的参数校验器。如果使用了非 Spring Boot 默认的参数校验器,需要在 pom.xml 文件中引入对应的校验依赖,并在方法参数上使用对应的校验注解。例如,如果使用了 jodd-validator,可以在 pom.xml 文件中添加以下依赖:
```
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-validator</artifactId>
<version>5.0.11</version>
</dependency>
```
然后在方法参数上使用 jodd-validator 提供的校验注解,例如 @Min、@Max、@Length 等。