Java 使用Guice将play.Environment注入Jackson序列化程序
杰克逊2.10.1, Guice 4.2.2, 播放2.7.2 我正在尝试将play.Environment对象注入自定义Jackson序列化程序,如下所示:Java 使用Guice将play.Environment注入Jackson序列化程序,java,playframework,jackson,guice,Java,Playframework,Jackson,Guice,杰克逊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); } publi
@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());
}
}
@Singleton
公共类PathSerializer扩展了StdSerializer{
@注入
环境;
公共路径序列化程序(){
这个(空);
}
公共路径序列化程序(t类){
超级(t);
}
@凌驾
public void serialize(路径值、JsonGenerator生成器、SerializerProvider提供程序)引发IOException{
Path Path=environment.rootPath().toPath().relativize(value.toabsolutionPath());
generator.writeString(path.toString());
}
}
但是,当调用此序列化程序时,会抛出NullPointerException
,因为environment
是null
使用@JsonSerialize(using=PathSerializer.class)
注释调用此自定义序列化程序。据我所知,当初始化此序列化程序时,它由Jackson而不是Guice管理,因此无法注入环境,因为PathSerializer
不是Guice管理的bean
使用Spring,您似乎可以根据使用@可配置的注释。但似乎没有一部戏剧能与之媲美
如何做到这一点?最后,我决定放弃play.Environment,并使用String base=new File(“.”.getCanonicalPath()获取基本路径代码>这更直截了当。
然后我用stringrelative=newfile(base).toURI().relatize(newfile(value.toString()).toURI()).getPath()将其相对化代码>