2

I need to do some cleanup when guice servlet is removed. Is it possible to hook into the servlet destruction when using a guice servlet? I need to use the Injector to do the cleanup work.

I can override the contextDestroyed method in GuiceServletContextListener, but then how do I get access to the injector?

Is there a better way to react to servlet destruction?

nfechner
  • 17,295
  • 7
  • 45
  • 64
lexicalscope
  • 7,158
  • 6
  • 37
  • 57

1 Answers1

3

I can override the contextDestroyed method in GuiceServletContextListener, but then how do I get access to the injector?

You could do it like this:

public class MyGuiceServletConfig extends GuiceServletContextListener {
    private final Injector injector = Guice.createInjector(new ServletModule());

    @Override
    protected Injector getInjector() {
        return injector;
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        injector.getInstance(MyCleanUp.class);      
    }
}

Or like this:

public class MyGuiceServletConfig extends GuiceServletContextListener {

    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule());
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Injector injector = (Injector) sce.getServletContext()
                                          .getAttribute(Injector.class.getName());      
    }
}
eiden
  • 2,329
  • 19
  • 19