Practical advice on using Jersey and Guice for RESTful service - java

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.

Guice integration with Jersey has not stagnated. The opposite is true. Thanks to Paul and his cohorts behind Jersey, the latest 1.7 release contains a special JerseyServletModule class to work with Guice-based servlets. Guice-based constructor injection into JAX-RS resource works! The issue is using JAX-RS annotations such as #QueryParam in the constructor of a JAX-RS resource. You don't need it! You use Guice for POJO injection all the way including singletons. Then JAX-RS is just icing on the cake for parsing HTTP-based RESTful APIs such as URL path, query parameters, content-type and etc. You don't need an "industrial strength" example either. Both Guice and Jersey are already battle tested. You just need a complete working example to see how it works. Then you can experiment advanced features on your own. Check out the following link for a complete example using Guice 3.0 and Jersey 1.7, which are all latest releases:
http://randomizedsort.blogspot.com/2011/05/using-guice-ified-jersey-in-embedded.html

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

Inspired by Sunnys sample application I've created a similar sample project that uses standard WAR files for deployment, e.g. in Apache Tomcat. You can find the project here:
https://github.com/danbim/template-guice-jersey-tomcat
Have fun!
Daniel

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)

I was having similar problems initially trying to use Guice to do constructor injection on my Jersey annotated classes, but eventually got it working, albeit with a fairly trivial application.
I followed the instructions here: jersey-guice javadoc
The trick in my case was that I needed to remove the standard Jersey configuration from my web.xml (like the Jersey ServletContainer) and keep only the Guice listener and Guice filter. Once I did that Guice was being called to create my JAX-RS annotated object, and Jersey was injecting my JAX-RS annotated methods (like #GET, etc.) as expected.

Although Sunny Gleason's example is great, it is a bit outdated now.
So, after struggling a lot today trying to make Guice and Jersey play nice with each other, I created the following sample project to get you started:
https://github.com/MaliciousMustard/gradle-guice-jersey-jetty
This project is using the following technologies:
Guice for DI
Jersey for the RESTful API
Jackson for POJO to JSON mapping
Jetty for the web-server
Gradle
I guess the most important thing is that you don't have to explicitly specify every new resource class you're adding. As long as you're adding them to the package that is being scanned (look at malicious.mustard.modules.JerseyModule), they will be found automatically!

GWizard includes a module that gives you out-of-the-box integration between Jersey2 and Guice. Here's an example of a complete JAX-RS service:
public class Main {
#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();
}
}
Note that this is based on the Squarespace jersey2-guice adapter, which may not function properly with future point releases of Jersey. GWizard also offers a RESTEasy JAX-RS module, which is preferred.
Here is a blog entry about this that might help: http://blorn.com/post/107397841765/guice-and-jersey-2-the-easy-way

The Jersey-Guice plugin Javadoc provides a pretty good description:
http://jersey.java.net/nonav/apidocs/1.1.5/contribs/jersey-guice/com/sun/jersey/guice/spi/container/servlet/package-summary.html

These examples were all great starts for me, but I wanted a full MVC stack using Jersey-Guice at it's core. I've been working on refining that for sometime. As of this week this MVC stack is fully deployed to Maven Central repository as an archetype. This means you can now create a new Jersey-Guice stack with one Maven command:
mvn archetype:generate \
-DarchetypeGroupId=org.duelengine \
-DarchetypeArtifactId=duel-mvc-archetype \
-DarchetypeVersion=0.2.1
This automatically generates your own project with you specified package naming so you don't have to manually edit a template project.
See the project Readme.md for more details: https://bitbucket.org/mckamey/duel-mvc
Details on the dual-side views (client-side template & server-side views) I use are here: https://bitbucket.org/mckamey/duel but you could replace with whatever you use.

I found an interesting project for lightweight Jetty+Guice+Jackson web services: https://github.com/talis/jersey-common/

I created a Guice 4.2, Jetty 9.4 and Jersey 2.7 sample application:
https://github.com/bnsd55/jetty-jersey-guice-starter-kit
As Sunny said:
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.

Related

How does jersey handles #pathparam injection internally?

I have been using jersey framework for developing restful web service in java for about a month now but somehow one thing i cant seem to comprehend is how does jersey handles #pathparam injection in resource methods,I know that hk2 is used under the hood for dependency injection in jersey and i know that abstract binder and factories are used for custom injection but i want some clear docs referring to the process of how does #Pathparam get injected into the method i.e step by step breakdown of some sort. I also came across the term ValueFactoryProvider while searching but all of it was pretty vague.
Have a look at PathParamValueParamProvider in the jersey-server artifact. This seems to where the magic happens together with implementations of MultivaluedParameterExtractor.
They are internal classes so I could not easily find any good javadoc. Looking at the sourcecode though, there are good comments which could help you break it down.

Don't quite understand the mechanism of Dependancy Injection in Struts2 XWork

I'm new to IOC and learning from source code of Struts2 framework currently.
Through learning, I've got some basic understanding of the framework like how ActionInvocation handlers interceptors etc.
But when I was trying to figure out the mysterious (to me at least) Dependency Injection part, I got completely lost.
The inject mechanism specified in package com.opensymphony.xwork2.inject is hard to comprehend. How exactly does the ContainerImpl.inject(Object) do all the work?
Or, where should I start in order to understand DI?
Personally I found this resource useful. For others who like to dig old, very old user guide can download Guice 1.0 User's Guide.pdf. As Dave mentioned
S2 uses an old (old!), hacked version of Guice for its DI.
So, you can use this page as a starting point for Dependency Injection with Struts2.
P.S.:
About ContainerImpl.inject(Object)
Injects dependencies into the fields and methods of an existing object.
It's not mysterious because Guice like Spring autowires a bean. Spring like Guice can use annotations to wire object dependencies.

Use Spring module without using Spring and Maven?

I'm currently working on a project that involves building a REST api using JavaEE. The setup of the project is Tomcat, Hibernate, Wink and Jackson Json for the different json-views. At the moment the unit testing of the rest resources is very poor, we've written custom classes that using introspection find the method that corresponds to a given resource but it is getting in our way (all the workarounds that we need to do in order to execute a simple unit test). I did a little research and found this.
My question is how to "install(add)" the MockServletInvocationTest class and its dependencies to the project? We're not using Maven, nor Spring. Is there a way to use Spring modules (I think this mock class is in the Spring test-module) outside Spring and if yes, how?
I found a solution, so for those who are interested: just add the following jars to your WebContent/WEB-INF/lib:
spring-test-xx.jar
spring-core-xx.jar
wink-component-test-support-xx-incubating.jar
commons-logging-xx.jar
And everything workds fine.

Resolve EJB Dependencies without a container

I am currently working on a solution for testing EJB 3 Services with JUnit.
(Yes, I have looked at ejb3unit but it doesn't work for me. Yes, I have looked at container-integrated testing with openEJB but that didn't work out neither..)
So my question is what would be the way for resolving #EJB annotated Dependencies? And I don't mean by using a DI Framework like Weld, Guice or Spring. The solution should be applicable for plain old JUnit Tests -> without using an EJB Container like JBoss, Glassfish or openEJB.
I was able to replace the injection of the entity manager via #PersistenceContext with a little hack using java reflections. So how would I do that for dependencies with #EJB annotation?
(I wouldn't mind building and resolving the dependency tree myself, just looking for ideas ;) )
Greetings from Germany,
p.s.
Not sure why you're against the solution you proposed.
I was about to offer stuff like Arquillian, but hey - you don't want to have a container involved.
I just want to be sure about the reason you don't want container, before I move on to some ideas (though I did not test them) -
With JBoss AS 7.x deployment time of enterprise application servers was vastly reduced,
Not to mention that with Arquillian you have a deployment API, and you can decide what you will deploy (i.e - deploy for example just a single bean for a given test).
However, I do respect you question, so here are some ideas -
A. You mentioned you managed to inject an EntityManager using reflection - how did you do that? Why not apply the same to your beans?
B. If you're encountering problems with A, why not develop your own injection code , based on cglib , for example (in order to create Proxy not just for interface, but also for classes).
This way, when an object of the class is created,
you will be able to intercept the default CTOR, and scan for fields annotated with #Ejb.
I would suggest using some sort of configuration file that maps for each bean interface how to instantiate an appropriate class, and run this flow recurisevely (as the injected bean might have a field with #EJB annotation as well).
Pay attention that if you decide to use this method of work, you'll be implementing some sort of "mini dependnecy injection framework" - besides the fact that personally I would be interested in seeing your code ( :) ) I think you should carefully think why you don't want to use an "already made solution.
Note regarding the Arquillian suggestions, that still requires an EJB Container like JBoss, GlassFish, or OpenEJB.
If the problem is just finding and including all the dependencies, try this jar that includes all the required dependencies for EJB Lite:
http://repo1.maven.org/maven2/org/apache/openejb/openejb-lite/4.0.0/openejb-lite-4.0.0.jar
Include that in your test classpath (no other jars needed) then just boot the embedded container:
EJBContainer container = EJBContainer.createEJBContainer();
MyBean bean = (MyBean) container.getContext().lookup("java:global/myModleName/MyBean");
Working example here
Have you look at Arquillian?
You can find all the documentation on the project page: http://www.jboss.org/arquillian.html

Spring 3 Annotations

I can't get spring annotations to work at all, I'm just trying to get the simplest thing to work...
.../mycontext/something -> invokes method:
#RequestMapping(value = "/something")
#ResponseBody
public String helloWorld() {
System.out.println("hello world");
return "Hello World";
}
My main problem is no matter how hard I try, I can't find a complete SIMPLE example of the configuration files needed, every spring tutorial is filled with junk, I just one one controller to handle a request with a mapping and can't get it to work
does anyone know of a simple and complete spring example. pet-clinic is no good, it's way too complicated, I have a tiny basic use case and it's proving to be a real pain to get working (this always happens with Spring)
You should try Spring Roo. It will generate a simple Spring application for you using simple commands and then you can incrementally extend it. It is a great tool for learning Spring as well as for rapid application development.
You can also find several examples of Spring 3.0 MVC framework.
the absolute simplest alternative if you're familiar with Eclipse is to use SpringSource Tool Suite (Eclipse plugins)
This product has a tcServer bundled inside.
By default, STS will start with "dashboard" page in the editor window. From here, you can click on creating a controller as demonstrated by this screenshot:
This is a quite simple controller and all you have to do to get it deployed on the bundled tcServer (Tomcat with some extra management features) is to click "next" a few times in the wizard.
That's a very good starting point for doing your own testing!
I endorse this blog post,Layered architecture with Hibernate and Spring. It was a great help for me when I tried to move from the declared xml approach to annotations. It contains the usages of annotations in Entity, Dao and Service layers.
I'd recommend you checkout some of projects from here
and try going trough book spring in action(manning) they give very good example on how to use aspects
or refer to this question

Categories

Resources