Question

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

Was it helpful?

Solution

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
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top