JAX-RS resources in JAR files: how to use CDI to register it with the JAX-RS runtime

Imagine you are creating a JAX-RS resource called Resource, and bundling it into a JAR called resource.jar, as a reusable service.  A developer creating a WAR would use your JAR in WEB-INF/lib, ensure that the JAX-RS runtime is started, and the resource would be detected and exposed, right?

No, sadly, the JAX-RS runtime will not automatically be able to find resources from within JARs without some help. CDI to the rescue!

If we annotate our JAX-RS class with a CDI annotation, such as @ApplicationScoped or @RequestScoped, and include a beans.xml in our JAR, then CDI will inspect our JAR, register our resource as a CDI managed bean, and — as a side effect — also register our resource with the JAX-RS runtime.

If you don’t use this method, then the developer of the WAR has to do a little bit more work. He/she will have to write a javax.ws.rs.core.Application subclass and implement either the getSIngletons() or getClasses() method and mention our resource class explicity in there, in order to let JAX-RS runtime know about the Resource class.

By using CDI, we can make the life of a resource user—the developer of the WAR—easier.


Post a comment or leave a trackback: Trackback URL.


  • Aman  On September 3, 2012 at 2:20 pm

    Hi Parijat,

    I’ve a few jars which don’t have beans.xml under META-INF folder. These are third party jars like Dozer, Jackson. How can I use them?

    The Java EE 6 wouldn’t let me instantiate its beans. Could you please revert fast for I’m stuck with this now for an eon.

    • parijatmishra  On September 3, 2012 at 4:57 pm

      Since the third party jars don’t have a beans.xml (and they shouldn’t) and nor do the classes you wish to instantiate have any annotations on them (again, they shouldn’t — they are libraries), the Java EE runtime correctly does not auto-instantiate any classes from those jars. Think about it: a library author has no way of knowing which of the many classes bundled in the jar a potential consumer might want to instantiate — this decision is application and logic specific and is rightfully the task of the application owner.

      So, in order to use classes from those jars, you need to refer to them in your own beans and instantiate them yourself. Your own beans can be annotated as @ManagedBean etc. to let the Java EE runtime instantiate them. Your beans, in turn, should instantiate and initialize the classes you need from third-party jars.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: