如何将 ObjectIdResolver 注册到 Spring/Jackson 对象映射器,以便 Spring 实例化 ObjectIdResolver 类?我想在我的 ObjectIdResolver 类中使用依赖注入。
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;
}
}
订单.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>