diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponent.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponent.java index 77b74582b1..2732cd60b3 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponent.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponent.java @@ -24,6 +24,7 @@ import java.lang.annotation.Target; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonSerializer; +import com.fasterxml.jackson.databind.KeyDeserializer; import org.springframework.core.annotation.AliasFor; import org.springframework.stereotype.Component; @@ -31,9 +32,9 @@ import org.springframework.stereotype.Component; /** * {@link Component} that provides {@link JsonSerializer} and/or {@link JsonDeserializer} * implementations to be registered with Jackson when {@link JsonComponentModule} is in - * use. Can be used to annotate {@link JsonSerializer} or {@link JsonDeserializer} - * implementations directly or a class that contains them as inner-classes. For example: - *
+ * use. Can be used to annotate {@link JsonSerializer}, {@link JsonDeserializer}, or
+ * {@link KeyDeserializer} implementations directly or a class that contains them as
+ * inner-classes. For example:
* @JsonComponent
* public class CustomerJsonComponent {
*
@@ -71,4 +72,37 @@ public @interface JsonComponent {
@AliasFor(annotation = Component.class)
String value() default "";
+ /**
+ * Indicates whether the component should be registered as a type serializer and/or
+ * deserializer or a key serializer and/or deserializer.
+ * @return the component's handle type
+ */
+ Handle handle() default Handle.TYPES;
+
+ /**
+ * Specify the classes handled by the serialization and/or deserialization of the
+ * component. Necessary to be specified for a {@link KeyDeserializer}, as the type
+ * cannot be inferred. On other types can be used to only handle a subset of
+ * subclasses.
+ * @return the classes that should be handled by the component
+ */
+ Class>[] handleClasses() default {};
+
+ /**
+ * An enumeration of possible handling types for the component.
+ */
+ enum Handle {
+
+ /**
+ * Register the component as a Type serializer and/or deserializer.
+ */
+ TYPES,
+
+ /**
+ * Register the component as a Key serializer and/or deserializer.
+ */
+ KEYS
+
+ }
+
}
diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java
index f5739a6a3b..4f9145293e 100644
--- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java
+++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonComponentModule.java
@@ -23,6 +23,7 @@ import javax.annotation.PostConstruct;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
+import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.module.SimpleModule;
@@ -32,12 +33,14 @@ import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.core.ResolvableType;
+import org.springframework.core.annotation.AnnotationUtils;
/**
* Spring Bean and Jackson {@link Module} to register {@link JsonComponent} annotated
* beans.
*
* @author Phillip Webb
+ * @author Paul Aly
* @since 1.4.0
* @see JsonComponent
*/
@@ -67,23 +70,32 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar
Map beans = beanFactory
.getBeansWithAnnotation(JsonComponent.class);
for (Object bean : beans.values()) {
- addJsonBean(bean);
+ JsonComponent annotation = AnnotationUtils.findAnnotation(bean.getClass(),
+ JsonComponent.class);
+ addJsonBean(bean, annotation);
}
}
- private void addJsonBean(Object bean) {
+ private void addJsonBean(Object bean, JsonComponent annotation) {
if (bean instanceof JsonSerializer) {
- addSerializerWithDeducedType((JsonSerializer>) bean);
+ addSerializerForTypes((JsonSerializer>) bean, annotation.handle(),
+ annotation.handleClasses());
+ }
+ if (bean instanceof KeyDeserializer) {
+ addKeyDeserializerForTypes((KeyDeserializer) bean,
+ annotation.handleClasses());
}
if (bean instanceof JsonDeserializer) {
- addDeserializerWithDeducedType((JsonDeserializer>) bean);
+ addDeserializerForTypes((JsonDeserializer>) bean,
+ annotation.handleClasses());
}
for (Class> innerClass : bean.getClass().getDeclaredClasses()) {
if (!Modifier.isAbstract(innerClass.getModifiers())
&& (JsonSerializer.class.isAssignableFrom(innerClass)
- || JsonDeserializer.class.isAssignableFrom(innerClass))) {
+ || JsonDeserializer.class.isAssignableFrom(innerClass)
+ || KeyDeserializer.class.isAssignableFrom(innerClass))) {
try {
- addJsonBean(innerClass.newInstance());
+ addJsonBean(innerClass.newInstance(), annotation);
}
catch (Exception ex) {
throw new IllegalStateException(ex);
@@ -93,10 +105,39 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar
}
@SuppressWarnings({ "unchecked" })
- private void addSerializerWithDeducedType(JsonSerializer serializer) {
- ResolvableType type = ResolvableType.forClass(JsonSerializer.class,
- serializer.getClass());
- addSerializer((Class) type.resolveGeneric(), serializer);
+ private void addSerializerForTypes(JsonSerializer serializer,
+ JsonComponent.Handle handle, Class>[] types) {
+ for (Class> type : types) {
+ addSerializerWithType(serializer, handle, (Class) type);
+ }
+
+ if (types.length == 0) {
+ ResolvableType type = ResolvableType.forClass(JsonSerializer.class,
+ serializer.getClass());
+ addSerializerWithType(serializer, handle, (Class) type.resolveGeneric());
+ }
+ }
+
+ private void addSerializerWithType(JsonSerializer serializer,
+ JsonComponent.Handle handle, Class extends T> type) {
+ if (JsonComponent.Handle.KEYS.equals(handle)) {
+ addKeySerializer(type, serializer);
+ }
+ else {
+ addSerializer(type, serializer);
+ }
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ private void addDeserializerForTypes(JsonDeserializer deserializer,
+ Class>[] types) {
+ for (Class> type : types) {
+ addDeserializer((Class) type, deserializer);
+ }
+
+ if (types.length == 0) {
+ addDeserializerWithDeducedType(deserializer);
+ }
}
@SuppressWarnings({ "unchecked" })
@@ -104,6 +145,14 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar
ResolvableType type = ResolvableType.forClass(JsonDeserializer.class,
deserializer.getClass());
addDeserializer((Class) type.resolveGeneric(), deserializer);
+
+ }
+
+ private void addKeyDeserializerForTypes(KeyDeserializer deserializer,
+ Class>[] types) {
+ for (Class> type : types) {
+ addKeyDeserializer(type, deserializer);
+ }
}
}
diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java
index 035cb54e1c..3b2d01e429 100644
--- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java
+++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/jackson/JsonComponentModuleTests.java
@@ -16,6 +16,12 @@
package org.springframework.boot.jackson;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;
@@ -24,12 +30,14 @@ import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Tests for {@link JsonComponentModule}.
*
* @author Phillip Webb
* @author Vladimir Tsanev
+ * @author Paul Aly
*/
public class JsonComponentModuleTests {
@@ -73,6 +81,38 @@ public class JsonComponentModuleTests {
context.close();
}
+ @Test
+ public void moduleShouldRegisterKeySerializers() throws Exception {
+ load(OnlyKeySerializer.class);
+ JsonComponentModule module = this.context.getBean(JsonComponentModule.class);
+ assertKeySerialize(module);
+ }
+
+ @Test
+ public void moduleShouldRegisterKeyDeserializers() throws Exception {
+ load(OnlyKeyDeserializer.class);
+ JsonComponentModule module = this.context.getBean(JsonComponentModule.class);
+ assertKeyDeserialize(module);
+ }
+
+ @Test
+ public void moduleShouldRegisterInnerClassesForKeyHandlers() throws Exception {
+ load(NameAndAgeJsonKeyComponent.class);
+ JsonComponentModule module = this.context.getBean(JsonComponentModule.class);
+ assertKeySerialize(module);
+ assertKeyDeserialize(module);
+ }
+
+ @Test
+ public void moduleShouldRegisterOnlyForSpecifiedClasses() throws Exception {
+ load(NameAndCareerJsonComponent.class);
+ JsonComponentModule module = this.context.getBean(JsonComponentModule.class);
+ assertSerialize(module, new NameAndCareer("spring", "developer"),
+ "{\"name\":\"spring\"}");
+ assertSerialize(module);
+ assertDeserializeForSpecifiedClasses(module);
+ }
+
private void load(Class>... configs) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(configs);
@@ -81,11 +121,17 @@ public class JsonComponentModuleTests {
this.context = context;
}
- private void assertSerialize(Module module) throws Exception {
+ private void assertSerialize(Module module, Name value, String expectedJson)
+ throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
- String json = mapper.writeValueAsString(new NameAndAge("spring", 100));
- assertThat(json).isEqualToIgnoringWhitespace("{\"name\":\"spring\",\"age\":100}");
+ String json = mapper.writeValueAsString(value);
+ assertThat(json).isEqualToIgnoringWhitespace(expectedJson);
+ }
+
+ private void assertSerialize(Module module) throws Exception {
+ assertSerialize(module, new NameAndAge("spring", 100),
+ "{\"name\":\"spring\",\"age\":100}");
}
private void assertDeserialize(Module module) throws Exception {
@@ -97,6 +143,37 @@ public class JsonComponentModuleTests {
assertThat(nameAndAge.getAge()).isEqualTo(100);
}
+ private void assertDeserializeForSpecifiedClasses(JsonComponentModule module)
+ throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(module);
+ assertThatExceptionOfType(JsonMappingException.class).isThrownBy(() -> mapper
+ .readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class));
+ NameAndCareer nameAndCareer = mapper.readValue(
+ "{\"name\":\"spring\",\"career\":\"developer\"}", NameAndCareer.class);
+ assertThat(nameAndCareer.getName()).isEqualTo("spring");
+ assertThat(nameAndCareer.getCareer()).isEqualTo("developer");
+ }
+
+ private void assertKeySerialize(Module module) throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(module);
+ Map map = new HashMap<>();
+ map.put(new NameAndAge("spring", 100), true);
+ String json = mapper.writeValueAsString(map);
+ assertThat(json).isEqualToIgnoringWhitespace("{\"spring is 100\": true}");
+ }
+
+ private void assertKeyDeserialize(Module module) throws IOException {
+ ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(module);
+ TypeReference