When using the guice servlet extension is it possible to react to servlet destruction?

674 views Asked by At

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?

1

There are 1 answers

0
eiden On

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());      
    }
}