我有一个实用方法:

public static void MyUtility(ClassWhoDoesImportantThink instance,
                             Object params...){...}


通常我以以下方式调用此方法:

public class UsualClass{
  ...
  @Inject
  ClassWhoDoesImportantThink importantInstance;
  ...
  public aMethod(){
     ...

     UtilityClass.myItility(importantInstance, arg1, arg2);
     ...
  }
}


其中@Inject是Guice功能。
但是,也许存在将“ importantInstance”直接注入我的静态实用程序的方法吗?像:

public static void MyUtility( Object params...){
   ClassWhoDoesImportantThink instance =
     GuiceFeature.getObjectUsuallyInjected(ClassWhoDoesImportantThink.class);
   ... //Do job
}

最佳答案

MyUtility中:

  @Inject
  static ClassWhoDoesImportantThink importantInstance;


或者,或者:

  static ClassWhoDoesImportantThink importantInstance;
  @Inject static void setImportantInstance(ClassWhoDoesImportantThink importantInstance) {
    MyUtility.importantInstance = importantInstance;
  }


并在适当的Guice模块configure()方法中:

  requestStaticInjection(MyUtility.class);


Guice随后将在其初始设置期间注入静态变量或设置器,并且MyUtility静态方法可以简单地使用静态字段。

07-24 15:44