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..e11e0716d4 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 @@ -1,5 +1,5 @@ /* - * Copyright 2012-2017 the original author or authors. + * Copyright 2012-2019 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. @@ -24,16 +24,16 @@ 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; /** - * {@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: - *
+ * {@link Component} that provides {@link JsonSerializer}, {@link JsonDeserializer} or
+ * {@link KeyDeserializer} implementations to be registered with Jackson when
+ * {@link JsonComponentModule} is in use. Can be used to annotate implementations directly
+ * or a class that contains them as inner-classes. For example:
* @JsonComponent
* public class CustomerJsonComponent {
*
@@ -56,6 +56,7 @@ import org.springframework.stereotype.Component;
* @see JsonComponentModule
* @since 1.4.0
* @author Phillip Webb
+ * @author Paul Aly
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@@ -71,4 +72,44 @@ public @interface JsonComponent {
@AliasFor(annotation = Component.class)
String value() default "";
+ /**
+ * The types that are handled by the provided serializer/deserializer. This attribute
+ * is mandatory for a {@link KeyDeserializer}, as the type cannot be inferred. For a
+ * {@link JsonSerializer} or {@link JsonDeserializer} it can be used to limit handling
+ * to a subclasses of type inferred from the generic.
+ * @return the types that should be handled by the component
+ * @since 2.2.0
+ */
+ Class>[] type() default {};
+
+ /**
+ * The scope under which the serializer/deserializer should be registered with the
+ * module.
+ * @return the component's handle type
+ * @since 2.2.0
+ */
+ Scope scope() default Scope.VALUES;
+
+ /**
+ * The various scopes under which a serializer/deserialzier can be registered.
+ * @since 2.2.0
+ */
+ enum Scope {
+
+ /**
+ * A serializer/deserializer for regular value content.
+ * @see JsonSerializer
+ * @see JsonDeserializer
+ */
+ VALUES,
+
+ /**
+ * A serializer/deserializer for keys.
+ * @see JsonSerializer
+ * @see KeyDeserializer
+ */
+ 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..750327900f 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
@@ -1,5 +1,5 @@
/*
- * Copyright 2012-2018 the original author or authors.
+ * Copyright 2012-2019 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.
@@ -18,26 +18,36 @@ package org.springframework.boot.jackson;
import java.lang.reflect.Modifier;
import java.util.Map;
+import java.util.function.BiConsumer;
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;
+import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
+import org.springframework.boot.jackson.JsonComponent.Scope;
import org.springframework.core.ResolvableType;
+import org.springframework.core.annotation.MergedAnnotation;
+import org.springframework.core.annotation.MergedAnnotations;
+import org.springframework.core.annotation.MergedAnnotations.SearchStrategy;
+import org.springframework.util.Assert;
+import org.springframework.util.ObjectUtils;
/**
* Spring Bean and Jackson {@link Module} to register {@link JsonComponent} annotated
* beans.
*
* @author Phillip Webb
+ * @author Paul Aly
* @since 1.4.0
* @see JsonComponent
*/
@@ -72,38 +82,74 @@ public class JsonComponentModule extends SimpleModule implements BeanFactoryAwar
}
private void addJsonBean(Object bean) {
+ MergedAnnotation annotation = MergedAnnotations
+ .from(bean.getClass(), SearchStrategy.EXHAUSTIVE)
+ .get(JsonComponent.class);
+ Class>[] types = annotation.getClassArray("type");
+ Scope scope = annotation.getEnum("scope", JsonComponent.Scope.class);
+ addJsonBean(bean, types, scope);
+ }
+
+ private void addJsonBean(Object bean, Class>[] types, Scope scope) {
if (bean instanceof JsonSerializer) {
- addSerializerWithDeducedType((JsonSerializer>) bean);
+ addJsonSerializerBean((JsonSerializer>) bean, scope, types);
}
- if (bean instanceof JsonDeserializer) {
- addDeserializerWithDeducedType((JsonDeserializer>) bean);
+ else if (bean instanceof JsonDeserializer) {
+ addJsonDeserializerBean((JsonDeserializer>) bean, types);
+ }
+ else if (bean instanceof KeyDeserializer) {
+ addKeyDeserializerBean((KeyDeserializer) bean, types);
}
for (Class> innerClass : bean.getClass().getDeclaredClasses()) {
- if (!Modifier.isAbstract(innerClass.getModifiers())
- && (JsonSerializer.class.isAssignableFrom(innerClass)
- || JsonDeserializer.class.isAssignableFrom(innerClass))) {
- try {
- addJsonBean(innerClass.newInstance());
- }
- catch (Exception ex) {
- throw new IllegalStateException(ex);
- }
+ if (isSuitableInnerClass(innerClass)) {
+ Object innerInstance = BeanUtils.instantiateClass(innerClass);
+ addJsonBean(innerInstance, types, scope);
}
}
}
- @SuppressWarnings({ "unchecked" })
- private void addSerializerWithDeducedType(JsonSerializer serializer) {
- ResolvableType type = ResolvableType.forClass(JsonSerializer.class,
- serializer.getClass());
- addSerializer((Class) type.resolveGeneric(), serializer);
+ private boolean isSuitableInnerClass(Class> innerClass) {
+ return !Modifier.isAbstract(innerClass.getModifiers())
+ && (JsonSerializer.class.isAssignableFrom(innerClass)
+ || JsonDeserializer.class.isAssignableFrom(innerClass)
+ || KeyDeserializer.class.isAssignableFrom(innerClass));
}
- @SuppressWarnings({ "unchecked" })
- private void addDeserializerWithDeducedType(JsonDeserializer deserializer) {
- ResolvableType type = ResolvableType.forClass(JsonDeserializer.class,
- deserializer.getClass());
- addDeserializer((Class) type.resolveGeneric(), deserializer);
+ @SuppressWarnings("unchecked")
+ private void addJsonSerializerBean(JsonSerializer serializer,
+ JsonComponent.Scope scope, Class>[] types) {
+ Class baseType = (Class) ResolvableType
+ .forClass(JsonSerializer.class, serializer.getClass()).resolveGeneric();
+ addBeanToModule(serializer, baseType, types,
+ (scope == Scope.VALUES) ? this::addSerializer : this::addKeySerializer);
+
+ }
+
+ @SuppressWarnings("unchecked")
+ private void addJsonDeserializerBean(JsonDeserializer deserializer,
+ Class>[] types) {
+ Class baseType = (Class) ResolvableType
+ .forClass(JsonDeserializer.class, deserializer.getClass())
+ .resolveGeneric();
+ addBeanToModule(deserializer, baseType, types, this::addDeserializer);
+ }
+
+ private void addKeyDeserializerBean(KeyDeserializer deserializer, Class>[] types) {
+ Assert.notEmpty(types, "Type must be specified for KeyDeserializer");
+ addBeanToModule(deserializer, Object.class, types, this::addKeyDeserializer);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void addBeanToModule(E element, Class baseType, Class>[] types,
+ BiConsumer, E> consumer) {
+ if (ObjectUtils.isEmpty(types)) {
+ consumer.accept(baseType, element);
+ return;
+ }
+ for (Class> type : types) {
+ Assert.isAssignable(baseType, type);
+ consumer.accept((Class) type, element);
+ }
}
}
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..7a9af5f2df 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
@@ -1,5 +1,5 @@
/*
- * Copyright 2012-2018 the original author or authors.
+ * Copyright 2012-2019 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.
@@ -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