FasterXML / FasterXML/jackson-modules-base

GuiceInjectableValues doesn't seem to work correctly

未关闭
#179 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
guice
主要语言
Java
星标
180
派生
80
平均合并
3 小时 26 分钟
30 天内合并 PR
1

描述

Looking at the code of GuiceInjectableValues, it seems unable to handle string values, which is what you get by default:

```java
@Override
public Object findInjectableValue(
Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance
)
{
return injector.getInstance((Key) valueId);
}
```

We try to deserialize an object of class A:
```
package org.example;

import com.fasterxml.jackson.annotation.*;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

public class A
{
private final String name;

@Inject
@JsonCreator
A(@JacksonInject X x, @Assisted @JsonProperty("name") String name) {
this.name = name;
}

public String getName() {
return name;
}
}
```

But valueId, in findInjectableValue, takes the name of the class, which is a string and cannot be converted to a Key, and we get an ClassCastException.

We ended-up creating our own InjectableValues subclass to handle this correctly:
```java
package org.example;

import com.fasterxml.jackson.databind.*;
import com.google.inject.*;

public class WorkingGuiceInjectableValues extends InjectableValues
{
private final Injector injector;

public WorkingGuiceInjectableValues(Injector injector) {
this.injector = injector;
}

public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) {
try
{
return this.injector.getInstance(WorkingGuiceInjectableValues.class.getClassLoader().loadClass((String)valueId));
}
catch (ClassNotFoundException e)
{
throw new RuntimeException(e);
}
}
}
```

This is what the main of our small toy program looks like:
```java
package org.example;

import java.io.*;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.module.guice.*;
import com.google.inject.Guice;

public class Main
{
public static void main(String[] args) throws IOException
{
System.err.println("hello world");
var objectMapper = new ObjectMapper();
var injector = Guice.createInjector(new ObjectMapperModule(), new InjectionModule());
var aFactory = injector.getInstance(AFactory.class);
var a = aFactory.create("New instance of org.example.A !!!");
System.err.println("a name: " + a.getName());
var file = new File("a.json");
objectMapper.writer().writeValue(file, a);
var a2 = objectMapper.reader(new GuiceInjectableValues(injector)).readValue(file, A.class);
System.err.println("a2 name: " + a2.getName());
}
}
```

Version of guice: 5.1.0
Version of jackson-module-guice: 2.13.3

贡献指南

这个仓库没有索引到贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。