I ended up using Google Guice, which is a lightweight DI framework that integrates well with Jersey. Here's what I had to do:
First, I added dependencies in the 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 a DAO implemented as a singleton with an interface:
public interface MySingletonDao
{
// ... methods go here ...
}
and a concrete implementation:
@Singleton
public class ConcreteMySingletonDao implements MySingletonDao
{
// ... methods go here ...
}
Decorated the resource classes like so:
@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
{
// ... implementation goes here ...
}
}
Created a class that will do the 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 the server. In my functional test, that looks something like:
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();
}
The EmptyServlet
comes from Sunny Gleason's sample code given out as an answer at: https://stackoverflow.com/a/3296467 -- I originally had
root.addServlet(new ServletHolder(new ServletContainer(new PackagesResourceConfig("com.example.resource"))), "/*");
instead of the line
root.addServlet(EmptyServlet.class, "/*");
But that caused Jersey to try and perform the dependency injection instead of Guice, which caused runtime errors.