Support Kotlin parameter default values in handler methods

This commit adds support for Kotlin parameter default values
in handler methods. It allows to write:
@RequestParam value: String = "default"
as an alternative to:
@RequestParam(defaultValue = "default") value: String

Both Spring MVC and WebFlux are supported, including on
suspending functions.

Closes gh-21139
This commit is contained in:
Sébastien Deleuze
2023-06-21 18:49:11 +02:00
parent 254fb39567
commit f06cf21341
12 changed files with 679 additions and 41 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,6 +38,8 @@ class KotlinMethodParameterTests {
private val nonNullableMethod = javaClass.getMethod("nonNullable", String::class.java)
private val withDefaultValueMethod: Method = javaClass.getMethod("withDefaultValue", String::class.java)
private val innerClassConstructor = InnerClass::class.java.getConstructor(KotlinMethodParameterTests::class.java)
private val innerClassWithParametersConstructor = InnerClassWithParameter::class.java
@@ -52,6 +54,16 @@ class KotlinMethodParameterTests {
assertThat(MethodParameter(nonNullableMethod, 0).isOptional).isFalse()
}
@Test
fun `Method parameter with default value`() {
assertThat(MethodParameter(withDefaultValueMethod, 0).isOptional).isTrue()
}
@Test
fun `Method parameter without default value`() {
assertThat(MethodParameter(nonNullableMethod, 0).isOptional).isFalse()
}
@Test
fun `Method return type nullability`() {
assertThat(MethodParameter(nullableMethod, -1).isOptional).isTrue()
@@ -123,6 +135,8 @@ class KotlinMethodParameterTests {
@Suppress("unused_parameter")
fun nonNullable(nonNullable: String): Int = 42
fun withDefaultValue(withDefaultValue: String = "default") = withDefaultValue
inner class InnerClass
@Suppress("unused_parameter")