0lu*_*sz0 6 servlets dependency-injection guice servlet-listeners guice-servlet
由于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());
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过扩展GuiceServletContextListener类轻松完成.这是一个例子:
public class MyServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new MyGuiceModule(), new MyGuiceServletModule());
}
}
Run Code Online (Sandbox Code Playgroud)
这里MyGuiceModule是一个普通的GuiceModule,ServletModule是一个servlet模块.虽然Servlet-Container中没有main方法,但您应该将模块交给Servlet容器.这样guice可以在servlet容器中管理你的普通Injection模块.