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.
- Ensure the guice-servlet.jar is included in your project and is deployed with your build.
- 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>
- Create a servlet module, a class extending com.google.inject.servlet.ServletModule.
- 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);
- 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.
- Add the new module to the Guice servlet context listener, which should already be configured in web.xml.
- Remove the servlet and servlet-mapping from web.xml.