Tutorial: How to use JAX-RS and CDI together

Hi,

because it’s relative hard to figure out, how to do it, I would like to show you how to combine JAX-RS and CDI.

Preparation

You need

  • a Glassfish v3.x where we will run this application
  • Gradle at least in version 1.0

Let’s start with a minimal application “The Greeter”.
If you call “<your_host>/GreetMeWithJaxRSAndCDI/rest/greet/<NAME>” it should return “Hi, <NAME>. Today it’s the <DATE>”.

The webservice

That was easy. (I skipped the imports to increase the visibility) Now the Greeting class.

Now let’s add an empty beans.xml and a web.xml with this content

The important thing here is that you need to specify an servlet class which provides an entry point to an implementation of the JAX-RS api. Here I chose Jersey.

Before we can build this “beast” we need to add some dependencies.

So the complete build.gradle will look like this

Ok, let’s build, deploy and call it. If you use a standard glassfish installation, then this link should work http://localhost:8080/GreetMeWithJaxRSAndCDI/rest/greet/peter.

Hmm, doens’t seem to work, or? What’s the problem behind?

The problem here is, that CDI isn’t in place to instantiate the dependency.
Their are two solutions for this problem:

  1.  Let CDI instantiate the dependency, but let Jersey managed it
    This can be achived using @ManagedBean and a Jersey specific annotation.
  2. Let CDI instantiate the dependency and let CDI manage it.
    This can be achieved using @RequestScoped or other CDI specific annotations.

In this example I use the first approach. This means we need to add @ManagedBean to our service.

Ok, let’s do a retry. And violá it works.

Lessons learned

To use JAX-RS and CDI together you need to

  • Specify a servlet which handles the requests (this needs to be done also, when you didn’t want to use CDI)
  • Specify who instatiates and who manages the injected beans:
  • @ManagedBean : CDI instantiates it and Jersey manages the life-cycle
  • @RequestScoped : CDI instantiates and manages the bean

I hope this will help you a little bit.

As usual you’ll find the project on http://github.com/coders-kitchen/GreetMeWithJaxRSAndCDI.

 
20 Kudos
Don't
move!

2 thoughts on “Tutorial: How to use JAX-RS and CDI together



Leave a Reply

Your email address will not be published. Required fields are marked *