我有一个单身人士:
public class MySingleton{
public static getInstance(){//typical singleton getInstance
...
}
//fields
private static volatile instance;
@Inject
private AnotherClassInstanceThatIWantToInjectHere anotherClassInst_BlaBla;
private MySingleton(){
...
anotherClassInst_BlaBla.doSmth();//NullPointerException happens!
...
}
}
此NPE的原因是什么?是因为它是构造函数还是因为单例而发生?
解决方法:
调用MySingleton的构造函数时,instance为null. Guice必须先构造MySingleton实例,然后才能注入任何内容.
Guice有一个单例的概念:您可以在模块的单例范围内绑定该类,也可以将该类注释为@Singleton.然后您像往常一样注入:
@Singleton
public class MySingleton {
private AnotherClassInstanceThatIWantToInjectHere anotherClassInst_BlaBla;
@Inject public MySingleton(AnotherClassInstanceThatIWantToInjectHere anotherClassInst_BlaBla) {
this.anotherClassInst_BlaBla = anotherClassInst_BlaBla;
anotherClassInst_BlaBla.doSmth();
}
}