吉斯。注入静态方法

Iva*_*kyy 4 java dependency-injection guice

我有一个实用方法:

public static void MyUtility(ClassWhoDoesImportantThink instance, 
                             Object params...){...}
Run Code Online (Sandbox Code Playgroud)

通常我这样调用这个方法:

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

     UtilityClass.myItility(importantInstance, arg1, arg2);
     ...
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Dou*_*las 6

MyUtility

  @Inject
  static ClassWhoDoesImportantThink importantInstance;
Run Code Online (Sandbox Code Playgroud)

或者,另一种选择:

  static ClassWhoDoesImportantThink importantInstance;
  @Inject static void setImportantInstance(ClassWhoDoesImportantThink importantInstance) {
    MyUtility.importantInstance = importantInstance;
  }
Run Code Online (Sandbox Code Playgroud)

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

  requestStaticInjection(MyUtility.class);
Run Code Online (Sandbox Code Playgroud)

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