Guice - Inject dependency into a class with static helper methods

穿精又带淫゛_ 提交于 2019-12-05 02:56:58

It doesn't get much more clear than that Guice documentation but here's a unit test that shows an example of how you can use static injection:

public class StaticInjectionExample {

  static class SomeClass {}

  static class TagLib{
    @Inject
    static SomeClass injected;

    public static void taglibFunction(String foo) {
      injected.something(foo);
    }

  }

  static class TestModule extends AbstractModule {
    @Override
    protected void configure() {
      requestStaticInjection(TabLib.class);
    }
  }

  @Test
  public void test() {
    Injector injector = Guice.createInjector(new TestModule());
    TagLib receiver = injector.getInstance(TagLib.class);
    // Do something with receiver.injected
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!