6

由于ServletContextListener是由服务器创建的,而不是由Guice创建的,所以我找不到使它一起工作的方法。如何在ServletContextListener上获得guice注入器?向Guice注入依赖关系到ServletContextListener

也许有更好的方法来关闭服务,如记录器或持久性,然后在contextDestroyed方法执行并在contextInitialized初始化它们?

回答

7

扩展GuiceServlet放入servlet上下文的注射器,这样你就可以做这样的事情得到它:

public class MyServletContextListener implements ServletContextListener { 

    @Override 
    public void contextDestroyed(ServletContextEvent sce) { 
     Injector injector = (Injector) sce.getServletContext() 
              .getAttribute(Injector.class.getName());  
    } 
} 
5

可以延伸GuiceServletContextListener类很容易做到这一点。下面是一个例子:

public class MyServletConfig extends GuiceServletContextListener { 
    @Override 
    protected Injector getInjector() { 
     return Guice.createInjector(new MyGuiceModule(), new MyGuiceServletModule()); 
    } 
} 

这里MyGuiceModule是正常GuiceModule和servlet模块是一个servlet一个。尽管Servlet-Container中没有主要的方法,但您应该将模块交给Servlet容器。这样guice就可以在servlet容器中管理正常的注入模块。