吉斯。注入静态方法

时间:2016-02-15 21:43:57

标签: java dependency-injection guice

我有一种实用方法:

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

通常我会这样称呼这个方法:

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

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

@Inject是Guice的功能。 但也许存在一种注入" importantInstance"直接到我的静态工具? Smth喜欢:

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

1 个答案:

答案 0 :(得分:3)

MyUtility

  @Inject
  static ClassWhoDoesImportantThink importantInstance;

或者,或者:

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

并使用适当的Guice模块configure()方法:

  requestStaticInjection(MyUtility.class);

然后Guice会在初始设置期间注入静态变量或setter,而MyUtility静态方法可以简单地使用静态字段。