I have quite a few projects that is slowly being migrated from Java to Kotlin, but I'm facing a problem when changing from Java POJO to Kotlin data classes. Bean validation stops working in REST controllers. I have created a very simple project directly from https://start.spring.io to demonstrate the failure.
@SpringBootApplication
class RestValidationApplication
fun main(args: Array<String>) {
runApplication<RestValidationApplication>(*args)
}
@RestController
class Controller {
@PostMapping
fun test(@Valid @RequestBody request: Test) {
println(request)
}
}
data class Test(@field:NotNull val id: String)
and gradle:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.6.1"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
kotlin("jvm") version "1.6.0"
kotlin("plugin.spring") version "1.6.0"
}
group = "com.example"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_17
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "17"
}
}
Sending a request does not trigger the bean validation, but it throws a HttpMessageNotReadableException because id is NULL.
curl -X POST http://localhost:8080 -H "Content-Type: application/json" -d "{}"
I have tried both @Valid and @Validated and using @get:NotNull on the attributes, but nothing works. I see many others have the same problem and using a Java class from a Kotlin REST controller works.
Also changing to a non data class makes validation works. Anyone know if it's possible to get bean validation working with Kotlin data classes?
Make the field nullable even its not, and then add @field:NotNull
data class Test(@field:NotNull val id: String?)
This will stop kotlin validation to happen before javax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With