使用guice servlet扩展时,是否可能对servlet破坏做出反应?

问题描述:

当删除guice servlet时,我需要进行一些清理.使用guice servlet时是否有可能陷入servlet的破坏?我需要使用Injector进行清理工作.

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.

我可以在GuiceServletContextListener中覆盖contextDestroyed方法,但是如何访问注射器?

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

是否有更好的方法应对servlet破坏?

Is there a better way to react to servlet destruction?

我可以在GuiceServletContextListener中重写contextDestroyed方法,但是如何获得对注入器的访问权限?

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

您可以这样做:

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

或者像这样:

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