I ended up using Google Guice, which is a lightweight DI structure that blends well with Jersey. Here is what I had to do:
First, I added the dependencies in pom.xml:
<dependency> <groupId>com.google.inject</groupId> <artifactId>guice</artifactId> <version>3.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-guice</artifactId> <version>1.12</version> <scope>compile</scope> </dependency>
I wanted DAO to be implemented as a singleton interface with an interface:
public interface MySingletonDao {
and specific implementation:
@Singleton public class ConcreteMySingletonDao implements MySingletonDao {
Decorate resource classes as follows:
@Path("/some/path") @RequestScoped public class MyResource { private final MySingletonDao mySingletonDao; @Inject public MyResource(MySingletonDao mySingletonDao) { this.mySingletonDao = mySingletonDao; } @POST @Produces("application/json") public String post() throws Exception {
Created a class that will perform bindings:
public class GuiceConfig extends GuiceServletContextListener { @Override protected Injector getInjector() { return Guice.createInjector(new JerseyServletModule() { @Override protected void configureServlets() { bind(MyResource.class); bind(AnotherResource.class); bind(MySingletonDao.class).to(ConcreteMySingletonDao.class); serve("/*").with(GuiceContainer.class); } }); } }
I used Jetty instead of Glassfish to actually act as a server. In my functional test, it looks something like this:
private void startServer() throws Exception { this.server = new Server(8080); ServletContextHandler root = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); root.addEventListener(new GuiceConfig()); root.addFilter(GuiceFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)); root.addServlet(EmptyServlet.class, "/*"); this.server.start(); }
EmptyServlet
comes from the Sunny Gleason example code, issued as an answer at: fooobar.com/questions/85848 / ... - I originally had
root.addServlet(new ServletHolder(new ServletContainer(new PackagesResourceConfig("com.example.resource"))), "/*");
instead of string
root.addServlet(EmptyServlet.class, "
But that made Jersey try and inject dependencies instead of Guice, which caused runtime errors.