Skip to content

Guice and Jersey 2, the easy way

Jeff Schnitzer edited this page Mar 12, 2017 · 2 revisions

January 7, 2015

It's 2015, almost two years since the release of Jersey 2.0, and it still doesn't play nicely with Guice. The Jersey/Glassfish team decided to write their own dependency injection system from scratch and made a mess of it ("Static globals? Check. Configuration files in META-INF directories? Check. J2EE locked and loaded, SIR!"). There have been a few attempts at Guice integration but nothing that makes it easy.

Well here it is, easy:

<dependency>
    <groupId>org.gwizard</groupId>
    <artifactId>gwizard-jersey</artifactId>
    <version>${gwizard.version}</version>
</dependency>
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import org.gwizard.jersey.JerseyModule;
import org.gwizard.web.WebServer;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

public class Main {
    /** A standard JAX-RS resource class */
    @Path("/hello")
    public static class HelloResource {
        @GET
        public String hello() {
            return "hello, world";
        }
    }

    public static class MyModule extends AbstractModule {
        @Override
        protected void configure() {
            bind(HelloResource.class);
        }
    }

    public static void main(String[] args) throws Exception {
        Guice.createInjector(new MyModule(), new JerseyModule()).getInstance(Run.class).start();
    }
}

Run this and you have a REST service running on port 8080.

Now the bad news: gwizard-jersey uses the jersey2-guice adapter, which works by using reflection to punch values into private final fields in Jersey's static globals. I didn't even know you could do that! While passing the Kobayashi Maru test, this intrepid effort may fail for some future point release of Jersey. So we don't recommend you use it unless you absolutely 100% need Jersey.

Now the silver lining: If you change gwizard-jersey to gwizard-rest in the pom.xml and replace new JerseyModule() with new RestModule(), the same code works with the reliable RESTEasy implementation of JAX-RS. It comes with Guice integration builtin, and it implements the very same JAX-RS specification.

GWizard throws in many more features as optional guice modules, including configuration files, logging, and Hibernate/JPA. They're all very thin and noninvasive; even if you decide not to use GWizard, you may want to use the source code as a pattern.

https://github.com/gwizard/gwizard

https://github.com/gwizard/gwizard-example

original