Injecting dependencies to ServletContextListener with Guice

喜欢而已 提交于 2019-12-22 05:58:52

问题


Since ServletContextListener is created by the server, not by Guice I can't find a way to make it work together. How do I get guice injector at ServletContextListener?

Maybe there is better way to shutdown services like logger or persistance then doing it at contextDestroyed method and initialize them at contextInitialized?


回答1:


The extension GuiceServlet puts the injector in the servlet context, so you can get it by doing something like this:

public class MyServletContextListener implements ServletContextListener {

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



回答2:


You can do it easily with extending GuiceServletContextListener class. Here is an example:

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

Here MyGuiceModule is a normal GuiceModule and ServletModule is a servlet one. Whereas there is no main method in Servlet-Container, you should hand your module to Servlet container. That way guice could manage your normal Injection modules in a servlet container.



来源:https://stackoverflow.com/questions/8605419/injecting-dependencies-to-servletcontextlistener-with-guice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!