简体   繁体   中英

Guice. Inject to static method

I have an utility method:

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

Usually I call this method in way:

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

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

Where @Inject is Guice feature. But maybe it is exists a way to inject an "importantInstance" directly to my static utility? Smth like:

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

In MyUtility :

  @Inject
  static ClassWhoDoesImportantThink importantInstance;

Or, alternatively:

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

And in the appropriate Guice module configure() method:

  requestStaticInjection(MyUtility.class);

Guice will then inject the static variable or setter during its initial setup, and MyUtility static methods can simply use the static field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM