将服务注入自定义的Jackson序列化器 [英] Inject Service into custom Jackson Serializer
问题描述
我在以下情况下有问题:
Hi I have problem in the following scenario:
我正在将Spring 4.xx与Jackson 2.xx结合使用,并且我正在使用RESTful Web应用程序。我现在面临一个问题,我需要为其中一个模型进行一些自定义序列化,所以我使用了自定义序列化器,但是我也需要在序列化时从数据库中获取一些数据。因此,我尝试将Serivce注入到Serializer中,但它始终保持为空。
I'm using Spring 4.xx with Jackson 2.xx and I'm ompelenting a RESTful Web Application. I'm now faced with te problem that I need some custom serialzation for one of my models, so i used a custom serilaizer, but i also need to fetch some data out of the database while serializing. So I tried to inject my Serivce into the Serializer but it always stays null.
据我所知,如果直接实例化对象,就会发生这种情况,我猜是杰克逊做什么。但是还有什么方法可以使用依赖注入吗?
As far as I have read this happens if you instanciate your object directly, which I guess is what Jackson does. But is there any way to still use Dependency Injection?
此外,如果我让该类实现ApplicationContextAware接口并调用ApplicationContext#getBean(),它将永远挂起。
Also if I make the class implement the ApplicationContextAware interface and call ApplicationContext#getBean() it hangs forever.
下面是一些代码来说明我的问题
Here is some code to illustrate my problem
Serialzer.java
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中完成。
My configuration is mainly annotaion based, only the databse stuff is done in xml.
预先感谢
wastl
推荐答案
您可以使用@Configurable spring批注将Spring bean注入非spring bean中。
You can use @Configurable spring annotation to inject spring bean into the non spring beans.
一些说明操作方法: http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non .html
这篇关于将服务注入自定义的Jackson序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!