在JavaEE应用程序中注册Jackson MixIn [英] Register Jackson MixIn in JavaEE application
问题描述
基于此设置(在JavaEE应用程序中使用Jackson作为JAXB提供程序):如何注册我的 MixIn模块 ?
On the basis of this setup (using Jackson as JAXB-provider in a JavaEE application): How can I register my MixIn modules?
在使用JAX-RS客户端功能的客户端应用程序中,它会自动注册。我见过这个SO帖子,但我在哪里可以得到ObjectMapper来自?我试图在我的 ServletContextListener
中创建并在那里注册模块。但是当然mapper实例将在 contextInitialized
方法结束后处理。
In my client application using the JAX-RS client feature it is registered automatically. I've seen this SO post, but where do I get the ObjectMapper from? I've tried to create on in my ServletContextListener
and register the module there. But of course the mapper instance will be disposed after the contextInitialized
method ends.
推荐答案
使用这篇文章中的 ContextResolver
。使用 @Provider
注释,应该从扫描中拾取 ContextResolver
(假设您正在使用某种扫描;包扫描或类路径扫描)
Use a ContextResolver
as seen in this post. With the @Provider
annotation, the ContextResolver
should be picked up from the scanning (assuming you are using kind of scanning; package scanning or classpath scanning)
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
final ObjectMapper mapper = new ObjectMapper();
public ObjectMapperContextResolver() {
mapper.registerModule(new MixinModule());
}
@Override
public ObjectMapper getContext(Class<?> type) {
return defaultMapper;
}
}
会发生什么,是 MessageBodyReader / MessageBodyWrite
将调用 getContext
方法,以获取 ObjectMapper
What happens, is that the MessageBodyReader/MessageBodyWrite
provided by your Jackson JAX-RS provider, will call the getContext
method, to get the ObjectMapper
这篇关于在JavaEE应用程序中注册Jackson MixIn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!