我有在我宣佈我的靜態常量類:吉斯:與@Named註解的字段值爲null
public final class ConfigOptions {
public static final String FILE_PATH_SERVER = "/home/user/me/somefile";
}
然後我用吉斯將它綁定在我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
}
}
我主要按照here所示的方法,但不確定是否遺漏了一些東西。
此外,我確保導入正確的import com.google.inject.name.Named
。
你能否確認你讓Guice創建MyClass的實例,而不是用'new MyClass()'自己實例化它?通過現場噴射,如果您從未通過噴油器請求班級,該場會默默地保持「空」狀態。切換到構造函數注入也將有助於明確該類是否通過Guice提供。 –
啊,你撞到了頭上!我不讓Guice創建MyClass(Guice noob在這裏)。注入MyClass反而解決了它。你應該可以讓它成爲答案。謝謝:) –
完成。很高興爲您提供幫助,祝您好運! –