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容器中管理正常的注入模塊。