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

[亡魂溺海] 提交于 2019-12-07 23:04:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!