Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice with JAX-RS

Tags:

rest

jax-rs

guice

I am using Guice as my dependency injection framework. I'd like something that I can add that will make creating REST services easier.

I've had a look at guice-servlet and it works well for directing paths to HTTP servlets, but that's all it appears to do, I was expecting a JAX-RS like annotation syntax to work but it doesn't.

Having not actually used JAX-RS I've googled around and it appears that Jersey is the reference implementation for this but it looks like it uses its own dependency injection framework and doesn't work well with Guice. In addition it has 5+MB worth of dependencies which seems alot for what I am after.

Is Guice designed in such a way that it doesn't lend itself to JAX-RS, if so what else should I be doing?

like image 302
Cheetah Avatar asked Mar 12 '23 22:03

Cheetah


1 Answers

I think that maybe the guice-servlet module has misguided you. Guice is a DI framework. Period. The real goal of the guice-servlet module is not providing the servlet's and filter's shortcut declaration but giving support for the special scopes request and session. Those nice shorcut declarations are syntatic sugar.

Chosing a JAX-RS implementation in Java is a bit out of the question. You have several options (Jersey, Resteasy, Spring...). If you are going full JavaEE then you don't have to choose. You just use the annotations (and the DI) out of the box.

If you are not using a JavaEE server (just a web server like Tomcat or any other fancy thing like an Android app) then you must choose your implementation. If you are using DI also (which I recommend) then there is one more decision to make.

So you are not using JavaEE and you want to implement some REST API using JAX-RS and dependency injection. You do some research and end up choosing Jersey and Guice. Good choice, I've chosen those in my last projects too. Yes, the dependency graph of Jersey is a bit bloated. I know, it could be way better.

Now your problem is how to make it work together because Jersey uses it's own DI framework (HK2) which is a bad thing.

You have a lot of references on SO about Jersey-Guice integration. Your best bet is the Guice HK2 bridge.

What? You want a direct reference on SO? No problem, here is a good one. Don't forget to upvote the answer. ;-)

  • Jersey and Google Guice integration
like image 56
sargue Avatar answered Mar 19 '23 07:03

sargue