问题
Hi I have problem in the following scenario:
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?
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
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
}
}
}
My configuration is mainly annotaion based, only the databse stuff is done in xml.
Thank you in advance,
wastl
回答1:
You can use @Configurable spring annotation to inject spring bean into the non spring beans.
Some explanation how to do it: http://www.kubrynski.com/2013/09/injecting-spring-dependencies-into-non.html
回答2:
The Jackson ObjectMapper
allows you to inject a HandlerInstantiator
, which it will use to create JsonSerializer
s and JsonDeserializer
s (among other things).
In v4.1.3, Spring introduced a SpringHandlerInstantiator
, which implements this interface, and does all the autowiring for you.
So, all you need is configure your 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;
}
You can also set this property on a Jackson2ObjectMapperBuilder
, if you're creating your ObjectMapper
that way.
来源:https://stackoverflow.com/questions/27369842/inject-service-into-custom-jackson-serializer