簡體   English   中英

使用Guice向ServletContextListener注入依賴項

[英]Injecting dependencies to ServletContextListener with Guice

由於ServletContextListener是由服務器創建的,而不是由Guice創建的,因此無法找到讓它一起工作的方法。 如何在ServletContextListener中獲取guice注入器?

也許有更好的方法可以關閉logger或persistance之類的服務,然后在contextDestroyed方法中執行它並在contextInitialized中初始化它們?

擴展GuiceServlet將注入器放在servlet上下文中,因此您可以通過執行以下操作來獲取它:

public class MyServletContextListener implements ServletContextListener {

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

您可以通過擴展GuiceServletContextListener類輕松完成。 這是一個例子:

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

這里MyGuiceModule是一個普通的GuiceModule,ServletModule是一個servlet模塊。 雖然Servlet-Container中沒有main方法,但您應該將模塊交給Servlet容器。 這樣guice可以在servlet容器中管理你的普通Injection模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM