servletsdependency-injectionguiceservlet-listenersguice-servlet

Injecting dependencies to ServletContextListener with Guice


Since ServletContextListener is created by the server, not by Guice I can't find a way to make it work together. How do I get guice injector at ServletContextListener?

Maybe there is better way to shutdown services like logger or persistance then doing it at contextDestroyed method and initialize them at contextInitialized?


Solution

  • The extension GuiceServlet puts the injector in the servlet context, so you can get it by doing something like this:

    public class MyServletContextListener implements ServletContextListener {
    
        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            Injector injector = (Injector) sce.getServletContext()
                                              .getAttribute(Injector.class.getName());      
        }
    }