使用guice servlet扩展时,是否可能对servlet破坏做出反应? [英] When using the guice servlet extension is it possible to react to servlet destruction?

查看:70
本文介绍了使用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());      
    }
}

这篇关于使用guice servlet扩展时,是否可能对servlet破坏做出反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆