'Why do not work @Validated in spring boot 2.6.2
I have in my pom file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.2.Final</version>
</dependency>
my controller:
@RestController
@RequestMapping(value = "/api")
@Validated
public class ValueController {
@PostMapping(value = "/values")
public ResponseEntity<Object> createValues(@RequestParam @Min(10) int number) {
return ResponseEntity.status(CREATED).body(number);
}
}
if i send post: 127.0.0.1:8080/api/values?number=5 return 5, but i want exception, what i need? java 11, spring boot 2.6.2
Solution 1:[1]
This seems to happen when hibernate-validator
dependency is included in the classpath.
With the version of spring-boot-starter-validation
specified above, you no longer need the hibernate-validator
. Removing it should make it work as expected.
+--- org.springframework.boot:spring-boot-starter-validation -> 2.6.7
| +--- org.springframework.boot:spring-boot-starter:2.6.7 (*)
| +--- org.apache.tomcat.embed:tomcat-embed-el:9.0.62
| \--- org.hibernate.validator:hibernate-validator:6.2.3.Final
| +--- jakarta.validation:jakarta.validation-api:2.0.2
| +--- org.jboss.logging:jboss-logging:3.4.1.Final -> 3.4.3.Final
| \--- com.fasterxml:classmate:1.5.1
Solution 2:[2]
Add @Valid before @RequestParam as follows:
public ResponseEntity<Object> createValues(@Valid @RequestParam @Min(10) int number) {
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Azadi Yazdani |