views:

738

answers:

2

From what I can find online, the state of the art for Guice + Jersey integration has stagnated since 2008 when it appears both teams reached an impasse. The crux of the issue is that JAX-RS annotations perform field and method injection and this doesn't play nicely with Guice's own dependency injection.

A few examples which I've found don't go far enough to elucidate:

  • Iqbalyusuf's post on Jersey + Guice on Google App Engine Java suffers from a lot of boilerplate (manually getting and calling the injector). I want binding and injection should happen behind the scenes via Guice annotations.

  • Jonathan Curran's article Creating a RESTful service with Jersey, Guice, and JSR-250 gave me hope because it's much more current (2010), but went no further than showing how to start up a Jersey service inside of a Guice ServletModule. However, there are no examples of doing any real dependency injection. I suppose that was left as an exercise for the reader. Curran's post may in fact be the correct first step towards wiring up Guice and Jersey and so I plan on starting with that.

  • tantalizingly James Strachan writes:

    JAX-RS works well with dependency injection frameworks such as Spring, Guice, GuiceyFruit or JBossMC - you can basically pick whichever one you prefer.

    But I see no evidence that is true from a practitioner's point of view.

What I find lacking are practical examples and explanations on how to combine JAX-RS and Guice annotations. For instance:

  • I believe I cannot use constructor injection with any resource as Jersey wants to control this
  • I'm uncertain whether I can combine @Inject with @PathParam, @QueryParam, et al.
  • How to use injection in a MessageBodyWriter implementation

Does anyone have examples, preferably with source, of non-trivial application which combines Jersey and Guice without sacrificing one or the other in the process? I'm keeping on this road regardless, but the bits and pieces on the Jersey and Guice lists makes me think I'm repeating the work of others who came before me.

A: 

I believe I cannot use constructor injection with any resource as Jersey wants to control this

You cannot use guice's constructor injection because creation of resource is managed by jersey. In this case you can use jersey's @Inject annotation before constructor parameter you want to get injected:

public NewsResource(@Inject NewsService service)
Jonas
+2  A: 

I created a Guice/Jersey/Jetty/Jackson sample application here:

http://github.com/sunnygleason/j4-minimal

If you have any questions or suggestions for how to improve the example, feel free to message me via github. The goal is to make this a very accessible introduction to REST on the Java stack.

Hope this helps - have a great day!

-Sunny

Sunny Gleason