将服务注入自定义Jackson Serializer

时间:2014-12-09 01:07:06

标签: java spring serialization dependency-injection jackson

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

我使用Spring 4.xx和Jackson 2.xx并且我正在使用RESTful Web应用程序。我现在面临的问题是我需要为我的一个模型进行一些自定义序列化,所以我使用了自定义的serilaizer,但我还需要在序列化时从数据库中获取一些数据。所以我试着将我的Serivce注入Serializer但它总是保持为空。

据我所知,如果你直接设置你的对象会发生这种情况,我想这就是杰克逊所做的事情。但是还有什么方法可以继续使用依赖注入吗?

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

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

Serialzer.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中完成的。

提前谢谢你,

wastl

2 个答案:

答案 0 :(得分:1)

您可以使用@Configurable spring注释将spring bean注入非spring bean。

如何解释:http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html

答案 1 :(得分:1)

Jackson ObjectMapper允许您注入HandlerInstantiator,它将用于创建JsonSerializerJsonDeserializer(以及其他)。

在v4.1.3中,Spring引入了SpringHandlerInstantiator,它实现了此接口,并为您完成所有自动装配。

因此,您所需要做的就是配置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;
}

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

相关问题