Skip to main content

Command Palette

Search for a command to run...

Kotlin, Spring Boot and Validations

BindingResult does not validate ? Here is the solutio

Published
1 min read

Spring boot is an excellent choice for backends and with Kotlin it is even better. However, if you are running to validation issues with Kotlin, remember there is a simple issue with Kotlin Annotations.

class User(@NotNull user:String);
@Controller
@RequestMapping("/users")
class UserController {
    @PostMapping
    fun createUser(@Valid user: User, bindingResult: BindingResult): ModelAndView {
        return ModelAndView("someview", "user", user)
    }
}

Kotlin however confuses these sort of annotations and applies them to the constructor instead of the field. Solution for this is very simple.

class User(@field:NotNull user:String);

This tells the Kotlin that the annotation is field specific and not meant for constructor. You code should then work.

Normally I use spring boot as backend of frontend and to render templates and such. This issue took a lot of my time but I solved it eventually.

Reference:

https://stackoverflow.com/questions/52345291/bean-validation-not-working-with-kotlin-jsr-380

https://stackoverflow.com/questions/51350923/request-binding-not-working-for-kotlin-class