Guice BlazeDS’ MessageBroker

In a previous post (http://www.connorgarvey.com/blog/?p=132), I wrote about how to use Guice injection for Flex services.  I used web.xml to configure the MessageBrokerServlet and configured each Flex service to use Guice as a factory.  Since then, on this project, we’ve had to introduce new servlets.  Rather than continue to use web.xml’s verbose and fully-qualified-path based configuration, we moved to using Guice’s ServletModule class.  Here are the steps we followed.

  1. Ensure the guice-servlet.jar is included in your project and is deployed with your build.
  2. Add the Guice filter to web.xml.
    <filter>
      <filter-name>guiceFilter</filter-name>
      <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>
    <filter-mapping>
      <filter-name>guiceFilter</filter-name>
      <url-pattern>/*</url-pattern>
    </filter-mapping>
  3. Create a servlet module, a class extending com.google.inject.servlet.ServletModule.
  4. Override the configureServlets() method of ServletModule and add the message broker servlet configuration.
    this.bind(MessageBrokerServlet.class).in(Scopes.SINGLETON);
    final Map<String, String> params = new TreeMap<String, String>();
    params.put("services.configuration.file", this.context
        .getRealPath("WEB-INF/config/flex/services-config.xml"));
    this.serve("/messagebroker/*").with(MessageBrokerServlet.class, params);

    1. Normally, servlets configured in Guice are tagged with @Singleton.  Since the MessageBrokerServlet is third party, it’s marked as a singleton here, in the module.
  5. Add the new module to the Guice servlet context listener, which should already be configured in web.xml.
  6. Remove the servlet and servlet-mapping from web.xml.
Posted in Guice at October 20th, 2009. 4 Comments.