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?

@Validated...hibernate-validatordependency?2.4.13,2.5.7and2.6.1. Also tried to replaceorg.springframework.boot:spring-boot-starter-validationwithorg.hibernate.validator:hibernate-validator:7.0.1.Final. And of course both Kotlin1.5.xand1.6.0.@NotNull(assuming this is the JSR-303 one) actually create anullcheck in the generated constructor for the data class? Which would basically throw the error upon construction, which wouldn't allow to reach validation at all as it will fail much earlier in the process. Please add the full stacktrace on the server you get when this happens, as I think it fails upon object construction which basically stops the whole processing (which also explains why it would work on a regular java class).