1

Is the a reason why Guice injection doesn't work in a ServletConextListener?

Here is my code:

public class QuartzContextListener implements ServletContextListener {

    @Inject
    private DataAccess dataAccess;


    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println(dataAccess);
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

    }

Of course that:

  • In all other places of the app injection is working OK.
  • The above listener appears AFTER the Guice initialization.

Any idea?

bashan
  • 3,572
  • 6
  • 41
  • 58

2 Answers2

1

It won't work because Guice is not creating the instance of your QuartzContextListener. If you are using GuiceServletContextListener I suggest to use just one listener (Guice's one) and call yours from that one.

If that solution is not possible you can try the workaround of using static injection. Be careful, thought, because you say Guice is bootstraped before your listener but that may not be always the case.

To use static injection you can change your listener definition like this:

public class QuartzContextListener implements ServletContextListener {

    @Inject
    private static Provider<DataAccess> dataAccessProvider;

    ...
}

And then, from one of your Guice modules, request an static injection.

requestStaticInjection(QuartzContextListener.class)
sargue
  • 5,695
  • 3
  • 28
  • 43
  • Thanks. Converting to static and using "requestStaticInjection" seems to be working fine, though I am not sure it is the prettiest way... – bashan Apr 23 '16 at 17:54
0

What about extending GuiceServletContextListener:

class Example extends GuiceServletContextListener {
        @Override
        protected Injector getInjector() {
            return Guice.createInjector(new MyGuiceModule(), new MyGuiceServletModule());
        }
    }
Humberto Pinheiro
  • 1,082
  • 1
  • 13
  • 19
  • Why would I want to create a new Guice injector if I already did it in another listener? The intention of this listener is to read some info from db and then apply it on quartz sceduler. The problem, is that DataAcess can be accesible only after Guice finished initializing. It was my assumption that on this listener, Quartz already finished initializing and therefore injections should work. – bashan Apr 19 '16 at 16:57
  • Because servlet context listener is initialized by the container and not by guice. See http://stackoverflow.com/questions/8605419/injecting-dependencies-to-servletcontextlistener-with-guice. – Humberto Pinheiro Apr 19 '16 at 17:02