Injecting into static field in Guice

Tags:

To handle static field injection, call requestStaticInjection.

@ImplementedBy(ManagerImpl.class) // replaced by ManagerImpl automatically without bind(..)
interface Manager { }

class ManagerImpl implements Manager { }

class MyModule implements Module {
  public void configure(Binder binder) {
    binder.requestStaticInjection(App.class); 
  }
}

public class App {
  @Inject
  private static Manager manager;
  public static void main(String[] args) {
    Guice.createInjector(new Module[] { new MyModule() });
    manager.sayHi();
  }
}

Comments

2 responses to “Injecting into static field in Guice”

  1. Eric Landry Avatar
    Eric Landry

    Sweeeeeet!!! Just when I was starting to think about doing something fugly, I come across this perfect solution to my problem.

    Thanks a lot for this!!!

    Eric
    =)

  2. MKSeo Avatar
    MKSeo

    Glad that this helps. :)

Leave a Reply

Your email address will not be published. Required fields are marked *