【问题标题】:Injecting dependencies to ServletContextListener with Guice使用 Guice 将依赖项注入到 ServletContextListener
【发布时间】:2012-01-26 04:27:25
【问题描述】:

由于 ServletContextListener 是由服务器创建的,而不是由 Guice 创建的,所以我找不到让它一起工作的方法。如何在 ServletContextListener 中获取 guice 注入器?

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

【问题讨论】:

    标签: servlets dependency-injection guice servlet-listeners guice-servlet


    【解决方案1】:

    扩展 GuiceServlet 将注入器置于 servlet 上下文中,因此您可以通过执行以下操作来获取它:

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

    【讨论】:

      【解决方案2】:

      您可以通过扩展 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 容器中管理您的正常注入模块。

      【讨论】:

        猜你喜欢
        • 2011-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多