gpt4 book ai didi

java - 将服务注入(inject)自定义 Jackson 序列化器

转载 作者:行者123 更新时间:2023-12-01 12:09:11 30 4
gpt4 key购买 nike

您好,我在以下情况下遇到问题:

我正在使用 Spring 4.xx 和 Jackson 2.xx,并且我正在支持 RESTful Web 应用程序。我现在面临一个问题,我需要为我的模型之一进行一些自定义序列化,因此我使用了自定义序列化器,但我还需要在序列化时从数据库中获取一些数据。所以我尝试将我的 Serivce 注入(inject)到序列化器中,但它始终保持为空。

据我所知,如果你直接实例化你的对象,就会发生这种情况,我猜这就是 jackson 所做的。但是有什么方法仍然可以使用依赖注入(inject)吗?

此外,如果我让该类实现 ApplicationContextAware 接口(interface)并调用 ApplicationContext#getBean(),它就会永远挂起。

这是一些代码来说明我的问题

序列化器.java

public class TheSerializer extends JsonSerializer<MyObject>
implements ApplicationContextAware {

@Autowired
ITheService theService;

ApplicationContext ctx;

public vodi serialize(MyObject o, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
if(theService == null) {
theService = ctx.getBean(ITheService.class); //This is where it hangs
//If I don't do this I get a NPE if I try to use theSerivice
}
}
}

我的配置主要是基于注释的,只有数据库的东西是在xml中完成的。

提前谢谢您,

浪费

最佳答案

Jackson ObjectMapper 允许您注入(inject) HandlerInstantiator,它将用于创建 JsonSerializerJsonDeserializer >s(除其他外)。

在 v4.1.3 中,Spring 引入了一个 SpringHandlerInstantiator,它实现了此接口(interface),并为您完成所有 Autowiring 。

因此,您所需要做的就是配置您的ObjectMapper:

@Bean
public SpringHandlerInstantiator handlerInstantiator(AutowireCapableBeanFactory beanFactory)
{
return new SpringHandlerInstantiator(beanFactory);
}

@Bean
public ObjectMapper objectMapper(SpringHandlerInstantiator handlerInstantiator)
{
ObjectMapper mapper = new ObjectMapper();
mapper.setHandlerInstantiator(handlerInstantiator);
return mapper;
}

如果您以这种方式创建 ObjectMapper,您还可以在 Jackson2ObjectMapperBuilder 上设置此属性。

关于java - 将服务注入(inject)自定义 Jackson 序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27369842/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com