Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice - Inject dependency into a class with static helper methods

I'm still new to Guice and haven't used any DI frameworks before. After reading the official wiki and many other documents I'm still unable to wrap my head around it completely.

In my particular case I want to write a EL taglib function that uses some other (to-be-injected) class. As all taglib functions have to be declared as static, I can't just @Inject my dependency via constructor or setter. I thought of using the requestStaticInjection() method described in http://code.google.com/p/google-guice/wiki/Injections#Static_Injections but I unable to get it to work and haven't been able to find any good tutorial.

Thanks in advance for any help,

Arman

like image 591
Arman Avatar asked Aug 26 '13 23:08

Arman


1 Answers

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
  }
}
like image 68
condit Avatar answered Oct 04 '22 04:10

condit