![](/img/trans.png)
[英]Mapper gets null value for the field annotated with @JsonIgnore (resttemplate)
[英]Guice: value of field annotated with @Named is null
我有一個聲明靜態常量的類:
public final class ConfigOptions {
public static final String FILE_PATH_SERVER = "/home/user/me/somefile";
}
然后,我使用Guice將其綁定到我的ServletModule
:
public class MyServletModule extends ServletModule {
bind(String.class).annotatedWith(Names.named("filePath"))
.toInstance(ConfigOptions.FILE_PATH_SERVER);
// Also tried
// bindConstant().annotatedWith(Names.named("filePath")).to(ConfigOptions.FILE_PATH_SERVER)
// ... other bindings
}
我的GuiceServletContextListener
:
public class MyServletContextListener extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new MyServletModule());
}
}
最后,我嘗試使用filePath
:
public class MyClass {
@Inject
@Named("filePath")
private String filePath;
public MyClass() { ... }
public void doSomething() {
someotherThing.setFilePath(filePath); // But filePath is null
}
}
我大部分都遵循此處顯示的方法,但是不確定是否丟失了某些內容。
此外,我確保import com.google.inject.name.Named
了正確的import com.google.inject.name.Named
。
確認您要讓Guice創建MyClass的實例,而不是使用new MyClass()
自己實例化它們。 即使一個字段用@Inject
標記,Guice也只能在Guice負責創建包含該值的實例時設置該值。 使用字段注入,如果從未通過注入器請求類,則字段將保持為空。
切換到構造函數注入也將使您清楚是否通過Guice提供了該類,因為更改構造函數將固有地中斷任何直接調用而不會中斷Guice創建的引用:
public class MyClass {
private final String filePath;
@Inject public MyClass(@Named("filePath") String filePath) {
this.filePath = filePath;
// ...
}
// ...
}
*您也可以使用Injector.injectMembers(instance)或Binder.requestInjection(instance)誘使 Guice注入現有實例。 這些並不常見,可能使您難以在構造和注入實例的位置進行操作,但在遺留代碼和其他一些情況下可能會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.