Allow abstract serializers/deserializer in @JsonComponent

Previously JsonComponentModule tried to instantiate all
inner classes and failed with InstantiationException when
the class is abstract and extends JsonSerializer/JsonDeserializer.
With this change is now possible to have common logic inner abstract classes.

See gh-9443
pull/9539/head
Vladimir Tsanev 8 years ago committed by Stephane Nicoll
parent acda4f905f
commit 6ba7849094

@ -16,6 +16,7 @@
package org.springframework.boot.jackson;
import java.lang.reflect.Modifier;
import java.util.Map;
import javax.annotation.PostConstruct;
@ -78,8 +79,9 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar
addDeserializerWithDeducedType((JsonDeserializer<?>) bean);
}
for (Class<?> innerClass : bean.getClass().getDeclaredClasses()) {
if (JsonSerializer.class.isAssignableFrom(innerClass)
|| JsonDeserializer.class.isAssignableFrom(innerClass)) {
if (!Modifier.isAbstract(innerClass.getModifiers()) &&
(JsonSerializer.class.isAssignableFrom(innerClass)
|| JsonDeserializer.class.isAssignableFrom(innerClass))) {
try {
addJsonBean(innerClass.newInstance());
}

@ -59,6 +59,15 @@ public class JsonComponentModuleTests {
context.close();
}
@Test
public void moduleShouldAllowInnerAbstractClasses() throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
JsonComponentModule.class, ComponentWithInnerAbstractClass.class);
JsonComponentModule module = context.getBean(JsonComponentModule.class);
assertSerialize(module);
context.close();
}
private void assertSerialize(Module module) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
@ -85,4 +94,15 @@ public class JsonComponentModuleTests {
}
@JsonComponent
static class ComponentWithInnerAbstractClass {
private static abstract class AbstractSerializer extends NameAndAgeJsonComponent.Serializer {
}
static class ConcreteSerializer extends AbstractSerializer {
}
}
}

Loading…
Cancel
Save