Restful service with JAX RS and CDI on Glassfish

Making an RESTful service with JAX RS with CDI and deploying on Glassfish

I was working on a RESTful service with JAX RS on Glassfish and pieced together a working implementation with CDI dependency injection.


This REST service is pretty simple, when you access /test/hello?name=John with a GET, you will get “Hello world John” back. Note the @ManagedBean annotation – this will make CDI dependency injection working in a JAX RS instantiated service.

The HelloRepository is injected with CDI:

You can package this as a WAR file and deploy it on a Glassfish server. To make this work, you need a minimal web.xml in WEB-INF:

To enable CDI, you need an empty beans.xml in WEB-INF:

And to make JAX RS working correctly and set the root path, you need this class:

To set the context root, you could also add a glassfish-web.xml in WEB-INF – this is of course Glassfish specific.

After figuring this out, it is easy to configure and doesn’t need any complicated XML. I got the above configuration working on Glassfish 3 and 4.