DEV Community

Cover image for Spring Boot Validation in Kotlin with @field
Austin Vance for Focused

Posted on • Originally published at focused.io

Spring Boot Validation in Kotlin with @field

Recently I found myself needing to validate fields in a Spring Boot controller written in Kotlin. Here's the code I ended up with:


@Controller
@RequestMapping("api/sample")
class SampleController {
    @PostMapping
    fun post (@Valid @RequestBody request: SampleType){
        return ResponseEntity.ok().build()
    }
}

data class SampleType(@field:NotBlank info: String)
Enter fullscreen mode Exit fullscreen mode

The key is the @field in the data class. Without that, Kotlin will apply validation to the constructor parameters by default. This makes sense when you see it, but is less obvious when you're wading through your 10th Java based tutorial on Spring validation.

Hope this helps!

Top comments (1)

Collapse
 
buildbasekit profile image
buildbasekit

This trips people up a lot when moving from Java to Kotlin.

Another gotcha is nested validation. If you don’t add @valid on nested objects, validation silently won’t run even if @field: is correct.

Took me a while to notice that in a real API flow.

Kotlin + Spring works great, but these small differences from Java docs can be confusing.