Search code examples
javaguiceguice-servlet

Guice injection doesn't work in ServletContextListener


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?


Solution

  • 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)