Skip to content

Commit 454c041

Browse files
koenpuntbclozel
authored andcommitted
Recursively instantiate beans in arguments
This commit ensures that Java beans using primary constructors are properly instantiated when they're nested and that the instantiation algorithm is called recursively. Fixes gh-155
1 parent 94ff0a2 commit 454c041

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

spring-graphql/src/main/java/org/springframework/graphql/data/method/annotation/support/GraphQlArgumentInstantiator.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ else if (value != null && CollectionFactory.isApproximableCollectionType(value.g
8989
Class<?> elementType = typeDescriptor.getElementTypeDescriptor().getType();
9090
args[i] = instantiateCollection(elementType, (Collection<Object>) value);
9191
}
92-
else {
92+
else if (value instanceof Map) {
93+
args[i] = this.instantiate((Map<String, Object>) value, methodParam.getParameterType());
94+
} else {
9395
args[i] = this.converter.convertIfNecessary(value, paramTypes[i], methodParam);
9496
}
9597
}

spring-graphql/src/test/java/org/springframework/graphql/data/method/annotation/support/GraphQlArgumentInstantiatorTests.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,17 @@ void shouldInstantiatePrimaryConstructorNestedBeanLists() throws Exception {
103103
assertThat(result.getItems()).hasSize(2).extracting("name").containsExactly("first", "second");
104104
}
105105

106+
@Test
107+
void shouldInstantiateComplexNestedBean() throws Exception {
108+
String payload = "{\"complex\": { \"item\": {\"name\": \"Item name\"}, \"name\": \"Hello\" } }";
109+
DataFetchingEnvironment environment = initEnvironment(payload);
110+
PrimaryConstructorComplexInput result = instantiator.instantiate(environment.getArgument("complex"), PrimaryConstructorComplexInput.class);
111+
112+
assertThat(result).isNotNull().isInstanceOf(PrimaryConstructorComplexInput.class);
113+
assertThat(result.item.name).isEqualTo("Item name");
114+
assertThat(result.name).isEqualTo("Hello");
115+
}
116+
106117
private DataFetchingEnvironment initEnvironment(String jsonPayload) throws JsonProcessingException {
107118
Map<String, Object> arguments = this.mapper.readValue(jsonPayload, new TypeReference<Map<String, Object>>() {
108119
});
@@ -182,5 +193,24 @@ public void setName(String name) {
182193
this.name = name;
183194
}
184195
}
196+
197+
static class PrimaryConstructorComplexInput {
198+
final String name;
199+
200+
final Item item;
201+
202+
public PrimaryConstructorComplexInput(String name, Item item) {
203+
this.name = name;
204+
this.item = item;
205+
}
206+
207+
public String getName() {
208+
return this.name;
209+
}
210+
211+
public Item getItem() {
212+
return item;
213+
}
214+
}
185215

186216
}

0 commit comments

Comments
 (0)