How can I register an ObjectIdResolver to an Spring/Jackson object mapper so that the ObjectIdResolver class gets instantiated by Spring? I would like to use dependency injection in my ObjectIdResolver class.
ObjectIdResolver.java
@Component
public class UserIdResolver implements ObjectIdResolver {
@Autowired
UserConverter userConverter;
@Override
public void bindItem(ObjectIdGenerator.IdKey id, Object ob) { }
@Override
public Object resolveId(ObjectIdGenerator.IdKey id) {
return userConverter.convert((Integer)id.key);
}
@Override
public boolean canUseFor(ObjectIdResolver resolverType) {
return getClass().isAssignableFrom(resolverType.getClass());
}
@Override
public ObjectIdResolver newForDeserialization(Object c) {
return this;
}
}
Order.java
public class Order {
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id",
resolver = UserIdResolver.class,
scope = User.class
)
@JsonIdentityReference(alwaysAsId=true)
private User user;
..
}
spring-servlet.xml
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
p:indentOutput="true" p:simpleDateFormat="yyyy-MM-dd'T'HH:mm:ss.SSSZ" />
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean"
p:targetObject-ref="objectMapper" p:targetMethod="registerModule">
<property name="arguments">
<list>
<bean class="com.fasterxml.jackson.datatype.joda.JodaModule" />
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService">
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ResourceHttpMessageConverter" />
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
You can try another solution, a little bit more complexe, but you have the full control of deserialization.
Step 1 : Create a JpaEntityResolver
Step 2 : Create a custom SpringHandlerInstantiator that help jackson to define dynamically which
Step 3 : Register your handler to the ObjectMapper of jacksonHttpMessageConverter
Step 4 : Enjoy to use it on your controller