嗨,我在以下情况下有问题:
我正在将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
}
}
}
我的配置主要基于注释,只有databse内容是在xml中完成的。
先感谢您,
浪费
您可以使用@Configurable spring批注将spring bean注入非spring bean。
有关如何执行操作的一些说明:http : //www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句