我正在尝试实现最简单的Java程序,其中通过@Singleton
注入@Inject
对象。但是,在@Inject
之后,对象始终是null
。
我意识到我需要使用Guice绑定某种行为。我这样做是通过MyGuiceModule
,即extends AbstractModule
。但是MyGuiceModule
从未被调用过,所以我必须添加以下行:Injector injector = Guice.createInjector(new MyGuiceModule());
但这行不通。这是我的文件:
孤独对象
import javax.inject.Inject;
import javax.inject.Singleton;
@Singleton
public class LonelyObject {
public LonelyObject() {
System.out.println("LonelyObject Constructor");
}
public void alive() {
System.out.println("I AM ALIVE");
}
}
考试
public class TheTest {
// inject LonelyObject here
@Inject
LonelyObject L;
public TheTest() {
}
// use LonelyObject
public void doit() {
L.alive();
}
}
MyGuiceModule
import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import javax.inject.Inject;
public class MyGuiceModule extends AbstractModule {
@Override
protected void configure() {
System.out.println("MyGuiceModule extends AbstractModule");
// make sure LonelyObject is always instantiated as a singleton
bind(LonelyObject.class).asEagerSingleton();
}
}
主功能
public static void main(String[] args) {
System.out.println("main");
// this is only here so MyGuiceModule gets called, otherwise
// it will be ignored. this seems to be the only way I can see
// to configure Guice. note that the returned Injector is not used.
Injector injector = Guice.createInjector(new MyGuiceModule());
TheTest t = new TheTest();
// crashes here with Exception in thread "main" java.lang.NullPointerException
t.doit();
}
最佳答案
您将完全绕过Guice。
实际上,罪魁祸首是这一行:
TheTest t = new TheTest();
您不应该自己创建实例。相反,请Guice为您创建它:
TheTest t = injector.getInstance(TheTest.class);
一种替代方法是请求Guice为您直接在您的实例中注入字段(但这仅在集成旧版库时才建议这样做):
TheTest t = new TheTest();
injector.injectMembers(t);