如何将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;
    }

}


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>

最佳答案

您可以尝试其他解决方案,但要复杂一些,但是可以完全控制反序列化。

步骤1:建立JpaEntityResolver

public class JpaEntityResolver extends SimpleObjectIdResolver {

    private EntityManager em;

    private Class<? extends EntityType> entityClass;

    public JpaEntityResolver() {

    }

    public JpaEntityResolver(EntityManager em, Class<? extends EntityType> entityClass) {
        this.em = em;
        this.entityClass = entityClass;
    }

    @Override
    public Object resolveId(IdKey id) {
        Object resolved = super.resolveId(id);
        if (resolved == null) {
            resolved = findEntityById(id);
            bindItem(id, resolved);
        }
        return resolved;
    }

    private Object findEntityById(IdKey idKey) {
        Long id = (Long) idKey.key;
        return em.find(entityClass, id);
    }

    @Override
    public ObjectIdResolver newForDeserialization(Object context) {
        return new JpaEntityResolver(this.em, this.entityClass);
    }
}


第2步:创建自定义SpringHandlerInstantiator,以帮助杰克逊动态定义哪个

@Component
public class TsqBeanHandlerInstantiator extends SpringHandlerInstantiator {

    /** Logger. */
    protected static final Logger LOGGER = LoggerFactory.getLogger(TsqBeanHandlerInstantiator.class.getName());

    private final AutowireCapableBeanFactory beanFactory;

    private final EntityManager em;

    private List<Class<? extends EntityType>> tsqEntities = new ArrayList<>();

    /**
     * Create a new SpringHandlerInstantiator for the given BeanFactory.
     * @param beanFactory the target BeanFactory
     */
    public TsqBeanHandlerInstantiator(AutowireCapableBeanFactory beanFactory, EntityManager em) {
        super(beanFactory);
        this.beanFactory = beanFactory;
        this.em = em;
    }

    @PostConstruct
    public void init()
    {
        //We record all available entity for futur use.
        for (EntityType<?> entity : em.getMetamodel().getEntities()) {
            Class<? extends EntityType> entityClass = (Class<? extends EntityType>) entity.getJavaType();
            String className = entityClass.getName();
            tsqEntities.add(entityClass);
        }
    }

    @Override
    public JsonDeserializer<?> deserializerInstance(DeserializationConfig config, Annotated annotated, Class<?> implClass) {
        Class entityClass =  annotated.getRawType();
        LOGGER.debug("deserializerInstance : " + entityClass);
        return (JsonDeserializer<?>) this.beanFactory.createBean(implClass);
    }

    /** @since 4.3 */
    @Override
    public ObjectIdGenerator<?> objectIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
        Class entityClass =  annotated.getRawType();
        LOGGER.debug("objectIdGeneratorInstance : " + entityClass);
        return (ObjectIdGenerator<?>) this.beanFactory.createBean(implClass);
    }

    /** @since 4.3 */
    @Override
    public ObjectIdResolver resolverIdGeneratorInstance(MapperConfig<?> config, Annotated annotated, Class<?> implClass) {
        Class entityClass =  annotated.getRawType();
        if(!tsqEntities.contains(entityClass))
        {
            return super.resolverIdGeneratorInstance(config, annotated, implClass);
        }
        LOGGER.debug("resolverIdGeneratorInstance : " + entityClass);
        return new JpaEntityResolver(em, entityClass);
    }
}


步骤3:将您的处理程序注册到jacksonHttpMessageConverter的ObjectMapper

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    private @Autowired MappingJackson2HttpMessageConverter jacksonHttpMessageConverter;

    private @Autowired TsqBeanHandlerInstantiator tsqBeanHandlerInstantiator;

    @PostConstruct
    public void init(){
        ObjectMapper objectMapper = jacksonHttpMessageConverter.getObjectMapper();
        objectMapper.setHandlerInstantiator(tsqBeanHandlerInstantiator);
    }
}


第4步:喜欢在控制器上使用它

@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Bean> create(HttpServletRequest  request) throws IOException {
    // getting the posted value
    String body = CharStreams.toString(request.getReader());
    Bean bean = jacksonHttpMessageConverter.getObjectMapper().readValue(body, service.getBeanClass());
    Bean saved = service.save(bean);

    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(saved.getId()).toUri();
    return ResponseEntity.created(location).body(saved);
}

09-27 14:27