java-Guice.注入构造函数

我有一个单身人士:

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();
  }
}
上一篇:java-Guice嵌套通用类型绑定


下一篇:Google Guice之AOP