问题
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:
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());
}
}
来源:https://stackoverflow.com/questions/7915155/when-using-the-guice-servlet-extension-is-it-possible-to-react-to-servlet-destru