【问题标题】:Inject Service into custom Jackson Serializer将服务注入自定义杰克逊序列化器
【发布时间】:2015-02-06 19:23:22
【问题描述】:

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

我将 Spring 4.xx 与 Jackson 2.xx 一起使用,并且正在开发一个 RESTful Web 应用程序。我现在面临一个问题,我需要为我的一个模型进行一些自定义序列化,所以我使用了自定义序列化器,但我还需要在序列化时从数据库中获取一些数据。所以我尝试将我的 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中完成的。

提前谢谢你,

废话

【问题讨论】:

    标签: java spring serialization dependency-injection jackson


    【解决方案1】:

    Jackson ObjectMapper 允许您注入 HandlerInstantiator,它将用于创建 JsonSerializers 和 JsonDeserializers(除其他外)。

    在 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;
    }
    

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

    【讨论】:

      【解决方案2】:

      你可以使用@Configurable spring注解将spring bean注入到非spring bean中。

      一些解释如何做到这一点:http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-31
        • 1970-01-01
        • 1970-01-01
        • 2015-07-11
        • 2017-01-30
        • 1970-01-01
        相关资源
        最近更新 更多