mirror of
https://github.com/spring-projects/spring-boot.git
synced 2024-07-05 00:56:58 +08:00
Add @Name support for Kotlin value object binding
Fixes gh-24379
This commit is contained in:
parent
dc9cdb71f5
commit
d61724aada
@ -48,6 +48,7 @@ import org.springframework.util.Assert;
|
||||
* @author Madhura Bhave
|
||||
* @author Stephane Nicoll
|
||||
* @author Phillip Webb
|
||||
* @author Scott Frederick
|
||||
*/
|
||||
class ValueObjectBinder implements DataObjectBinder {
|
||||
|
||||
@ -202,7 +203,7 @@ class ValueObjectBinder implements DataObjectBinder {
|
||||
List<KParameter> parameters = kotlinConstructor.getParameters();
|
||||
List<ConstructorParameter> result = new ArrayList<>(parameters.size());
|
||||
for (KParameter parameter : parameters) {
|
||||
String name = parameter.getName();
|
||||
String name = getParameterName(parameter);
|
||||
ResolvableType parameterType = ResolvableType
|
||||
.forType(ReflectJvmMapping.getJavaType(parameter.getType()), type);
|
||||
Annotation[] annotations = parameter.getAnnotations().toArray(new Annotation[0]);
|
||||
@ -211,6 +212,11 @@ class ValueObjectBinder implements DataObjectBinder {
|
||||
return Collections.unmodifiableList(result);
|
||||
}
|
||||
|
||||
private String getParameterName(KParameter parameter) {
|
||||
return parameter.getAnnotations().stream().filter(Name.class::isInstance).findFirst().map(Name.class::cast)
|
||||
.map(Name::value).orElse(parameter.getName());
|
||||
}
|
||||
|
||||
@Override
|
||||
List<ConstructorParameter> getConstructorParameters() {
|
||||
return this.constructorParameters;
|
||||
|
@ -10,6 +10,7 @@ import org.springframework.core.ResolvableType
|
||||
* Tests for `ConstructorParametersBinder`.
|
||||
*
|
||||
* @author Stephane Nicoll
|
||||
* @author Scott Frederick
|
||||
*/
|
||||
class KotlinConstructorParametersBinderTests {
|
||||
|
||||
@ -187,6 +188,15 @@ class KotlinConstructorParametersBinderTests {
|
||||
assertThat(bean.value.get("bar")).isEqualTo("baz");
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `Bind to named constructor parameter`() {
|
||||
val source = MockConfigurationPropertySource()
|
||||
source.put("foo.string-value", "test")
|
||||
val binder = Binder(source)
|
||||
val bean = binder.bind("foo", Bindable.of(ExampleNamedParameterBean::class.java)).get()
|
||||
assertThat(bean.stringDataValue).isEqualTo("test")
|
||||
}
|
||||
|
||||
class ExampleValueBean(val intValue: Int?, val longValue: Long?,
|
||||
val booleanValue: Boolean?, val stringValue: String?,
|
||||
val enumValue: ExampleEnum?)
|
||||
@ -228,6 +238,8 @@ class KotlinConstructorParametersBinderTests {
|
||||
val stringValue: String = "my data",
|
||||
val enumValue: ExampleEnum = ExampleEnum.BAR_BAZ)
|
||||
|
||||
data class ExampleNamedParameterBean(@Name("stringValue") val stringDataValue: String)
|
||||
|
||||
data class GenericValue<T>(
|
||||
val value: T
|
||||
)
|
||||
|
Loading…
Reference in New Issue
Block a user