使用guice servlet模块注册web.xml监听器

时间:2013-04-27 10:07:12

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

我在我的项目中使用guice和guice servlet。 我可以使用serve(...)和filter(...)方法在servletmodule中映射servlet和过滤器。 如何在servlet模块中注册监听器(web.xml中的监听器标签)。 我正在使用HttpSessionAttributeListener。

我想在我的监听器中使用guice注入器。我尝试使用bindListener(..),但这似乎不起作用。

此致

2 个答案:

答案 0 :(得分:3)

我可以想到几个选择。

(1)正常注册侦听器(在web.xml中)并从servlet上下文属性中检索注入器。 GuiceServletContextListener在初始化后使用属性名Injector.class.getName()将注入器实例放入servlet上下文中。我不确定这是记录还是支持,因此您可能希望为注射器定义自己的属性名称并将其自己放在那里。只需确保您考虑了侦听器的初始化顺序 - 在调用GuiceServletContextListener之前,不会绑定注入器。

class MyListenerExample implement HttpSessionListener { // or whatever listener
    static final String INJECTOR_NAME = Injector.class.getName();

    public void sessionCreated(HttpSessionEvent se) {
        ServletContext sc = se.getSession().getServletContext();
        Injector injector = (Injector)sc.getAttribute(INJECTOR_NAME);
        // ...
    }
}

(2)如果您使用的是Java Servlets API 3.0+,则可以在ServletContext上调用addListener。我建议你在创建注射器时做到正确,尽管你可以在任何地方做到。这种方法对我来说有点笨拙,但应该有用。

public class MyServletConfig extends GuiceServletContextListener {
    ServletContext servletContext;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        servletContext = event.getServletContext();

        // the super call here is where Guice Servlets calls
        // getInjector (below), binds the ServletContext to the
        // injector and stores the injector in the ServletContext.
        super.contextInitialized(event);
    }

    @Override
    protected Injector getInjector() {
        Injector injector = Guice.createInjector(new MyServletModule());
        // injector.getInstance(ServletContext.class) <-- won't work yet!

        // BIND HERE, but note the ServletContext will not be in the injector
        servletContext.addListener(injector.getInstance(MyListener.class));
        // (or alternatively, store the injector as a member field and
        // bind in contextInitialized above, after the super call)

        return injector;
    }
}

请注意,在上述所有组合中,不保证在GuiceFilter管道中调用侦听器。所以,特别是,尽管它可能有用,但我建议您不要依赖于侦听器中对Request-scoped对象的访问,包括HttpServletRequest和HttpServletResponse。

答案 1 :(得分:0)

基于guice documentationServletModule仅用于配置servlet和过滤器。

This module sets up the request and session scopes, and provides a place to configure your filters and servlets from.

因此,在您的情况下,您必须将您的监听器添加到web.xml并以某种方式获取注入器。