Search code examples
spring-bootkotlinbean-validation

Validation not working on Map keys in RestController


Using Spring Boot 2.2.6, given this Controller:

@RestController
@Validated
class MyController {
    @GetMapping("foo")
    fun getFirmwareVersionDifference(
        @RequestParam @Valid versions: @Valid Map<
            @Pattern(regexp = "a|b|c")
            String, String>
    ): String {
       // …
    }
}

I would expect the request foo?d=any to throw a ConstraintViolationException, but the controller is called normally.

I have a MethodValidationPostProcessor in my context and it works for other validations. If I change the RequestParam to @RequestParam @Valid @Length(min=3) installedFirmwareVersion: String it works as expected fine.

What am I missing?


Solution

  • This is a kotlin compiler bug / missing feature: https://youtrack.jetbrains.com/issue/KT-13228

    As documented in https://youtrack.jetbrains.com/issue/KT-35843 this is partially solved in kotlin 1.3.70.

    Here's how you can set the compiler flag in build.gradle.kts

    tasks.withType<KotlinCompile> {
        kotlinOptions {
            freeCompilerArgs = listOf("-Xemit-jvm-type-annotations")
            jvmTarget = "11" // at least 8 should work, I only tested 11
        }
    }