Spring RequestParam validation in Kotlin is not working

Viewed 1437

I am trying to validate @RequestParam in Kotlin, however it does not work. Currently I am using Kotlin 1.4.20, Spring boot 2.3.5, and java 1.8.

Here is my controller:

@Validated
@RestController
@RequestMapping("api/v1/")
class myController{

    @GetMapping("/age", produces = [MediaType.APPLICATION_JSON_VALUE])
    fun findArticlesByAge(@RequestParam @Valid @Min(6) age: Int): ResponseEntity<Article> =
            ResponseEntity
                .ok()
                .body(Article())
}

Hibernate validator is already in the effective pom:

      <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.6.Final</version>
      </dependency>

Request:

http://localhost:8080/api/v1/age?age=2

Response:

200

That is the simple validation which is not working, however I want to do more complex validations through custom annotations and ConstraintValidator. If I make it work with the simple case @Min(6) probably it will start working also with the custom annotation.

1 Answers

So there was a dependency missing:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

I added this and the validation started working. However, it throws 500 internal server error with the validation message, which can be fixed by a ControllerAdvice.

Related