【发布时间】: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