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

南楼画角 提交于 2019-12-06 04:57:30

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