How Spring deserializes query params into Kotlin data classes?

Viewed 152

Assume a Spring @RestController with a simple @GetMapping that accepts a VenueQuery dataclass as its parameter:


data class VenueQuery(
    val cityId: Long? = null,
    val countryIso: String? = null,
)

@RestController
open class VenueController {

    @GetMapping("/venues")
    open fun getVenues(
        request: HttpServletRequest,
        response: HttpServletResponse,
        venueQuery: VenueQuery
    ) { ... }
}

Runing the code as above, works "well". GET /venues?cityId=1&countryIso=CZ gets deserialised into VenueQuery(cityId=1, countryIso="CZ"}.

However, annotating the venueQuery function argument with @RequestParam causes the same request to be rejected with BAD_REQUEST "Missing required parameter 'venueQuery'". This makes sense, but renders the former case even more confusing.

After searching for quite some time I still can't answer the following questions:

  1. Where can I find a documentation that describes this behavior in more detail? I.e. any reference I could point to instead of relying on a one-time observation?
  2. Is the first case even an expected behavior?
  3. How does spring knows it should populate the venueQuery argument with query params, but not the request and response params? Does it infer by its types of servlet request/response?
  4. Generally I struggle to find any documentation (not a "how to" but documentation) about how the Spring annotations and principles apply in Kotlin. Are there any notable sources?

Thanks for any answers!

1 Answers
  1. Expected behavior?

Yes.

  1. How does spring knows it should populate the venueQuery argument with query params?

By its type. Try two of VenueQuery and see what happens.

  1. Generally I struggle to find any documentation...

Unless the behavior is markedly different, there’s no special mention for Kotlin. As for “notable sources”, I’ve always found the answers I’m looking for in their source code. Grab a cup of coffee and fire up a debugger, you’ll too.

Related