【问题标题】:Injecting play.Environment into Jackson serializer using Guice使用 Guice 将 play.Environment 注入 Jackson 序列化程序
【发布时间】:2020-02-06 01:50:44
【问题描述】:

杰克逊 2.10.1, Guice 4.2.2, 玩2.7.2

我正在尝试将 play.Environment 对象注入到自定义 Jackson 序列化程序中,如下所示:

@Singleton
public class PathSerializer extends StdSerializer<Path> {

  @Inject
  Environment environment;

  public PathSerializer() {
    this(null);
  }

  public PathSerializer(Class<Path> t) {
    super(t);
  }

  @Override
  public void serialize(Path value, JsonGenerator generator, SerializerProvider provider) throws IOException {
    Path path = environment.rootPath().toPath().relativize(value.toAbsolutePath());
    generator.writeString(path.toString());
  }
}

但是,当调用此序列化程序时,会抛出 NullPointerException,因为 environmentnull

使用@JsonSerialize(using = PathSerializer.class) 注释调用此自定义序列化程序。据我了解,初始化此序列化程序时,它由 Jackson 而不是 Guice 管理,因此无法注入环境,因为 PathSerializer 不是 Guice 托管 bean。

使用 Spring,您似乎可以按照 this 使用 @Configurable 注释。但似乎没有 Play 等价物。

我该怎么做?

【问题讨论】:

    标签: java playframework jackson guice


    【解决方案1】:

    最后我决定摆脱 play.Environment 并使用String base = new File(".").getCanonicalPath(); 获得基本路径,这更直接。 然后我用String relative = new File(base).toURI().relativize(new File(value.toString()).toURI()).getPath();相对化了它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-11
      • 2016-07-26
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多