在Jackson Serializer中没有解决CDI注入问题

在Jackson Serializer中没有解决CDI注入问题

问题描述:

我正在尝试在Jackson的 JsonSerializer<> 中注入一个 @RequestScoped 对象类:

I'm trying to inject a @RequestScoped object class in a Jackson's JsonSerializer<>:

public class DigitalInputSerializer extends JsonSerializer<DigitalInput>
{
    @Inject private UserRequestResources user;

    @Override
    public void serialize(DigitalInput value, JsonGenerator gen,
            SerializerProvider serializers) throws IOException,
            JsonProcessingException {

        gen.writeStartObject();
        gen.writeStringField("user", this.user.getMe().getUser());

在最后一行, this.user null

@RequestScoped
public class UserRequestResources
{

此对象类在项目的其他位置解析。
我正在使用Wildfly 8 J2EE实现。

This object class is resolved on whereever on other places of the project. I'm using Wildfly 8 J2EE implementation.

编辑:

我有一个配置jackson mapper的主要资源:

I've a main resource where I configure jackson mapper:

@ApplicationScoped
public class SerializationApplicationResources
{

  protected ObjectMapper mapper;

  @PostConstruct
  protected void initialize_resources() throws IllegalStateException
  {
    this.mapper = new ObjectMapper();

    SimpleModule module = new SimpleModule();

    module.addDeserializer(DigitalInput.class, new DigitalInputDeserializer());
    module.addSerializer(DigitalInput.class, new DigitalInputSerializer());

为了使用它,我只用 @Inject ,然后我有一个实例。

In order to use it, I only annotate my fields with @Inject, and then I've an instance of that.

@Inject protected SerializationApplicationResources jacksonResources;

那么,

this.jacksonResources.getMapper().writeValueAsBytes(entity);


可能没有简单的方法可以做到这一点因为as as其他人已经指出,杰克逊序列化的对象不是自动注入的,因为杰克逊不知道这个过程将如何发生。

There may not be simple way to do that because as others have pointed out, objects that Jackson serializes are not injected automatically as Jackson has no knowledge of how this process would happen.

但杰克逊确实有建立简单模块的扩展点那样做。例如,有Guice和OSGi模块:

But Jackson does have extension points for building simple modules that do just that. For example there are Guice and OSGi modules:

  • https://github.com/FasterXML/jackson-module-guice
  • https://github.com/FasterXML/jackson-module-osgi

两者都可以支持使用Jackson的 @JacksonInject 注释(表示注入位置以及使用的逻辑ID)来查找可注入对象使用模块想要的任何机制。
所以应该可以实现CDI注入模块,如果不存在(我不知道一个,但因为它应该是可行的,有人可能已经这样做了。)

both of which can support use of Jackson's @JacksonInject annotation (to denote where to inject, and what logical id to use) to find out injectable objects using whatever mechanism module wants to. So it should be possible to implement CDI-injection module, if one does not exist (I am not aware of one, but since it should be doable someone may already have done that).

这假设您想要注入的对象是由Jackson基于JSON创建的;在这种情况下,CDI实现本身通常无法访问它。

This assumes that the object you want injected is created by Jackson, based on JSON; in which case CDI implementation itself does not typically have access to it.