Monday, January 12, 2015

Injecting EJBs into JAX-RS Resources using CDI

If you've ever tried to inject an EJB into a JAX-RS v1.x resource using the @EJB annotation, you know it doesn't work.  There are some implementations of JAX-RS that have provided this functionality, but it is implementation specific, not necessarily part of the JAX-RS specification.  It can be over come though by using Contexts and Dependency Injection (CDI).  The steps below are the bare minimum for CDI to inject an EJB into a JAX-RS resource running on the WebSphere Liberty profile.  The steps use the project structure I outlined in a previous post that can be found here.

Enabling CDI


The first step is to enable CDI for the JAX-RS and EJB projects.  This can be accomplished by adding a file called beans.xml to both projects in the standard locations.  For JAR projects (the EJB project in this case), the file is added to the META-INF folder.  In an Eclipse Maven project, this is located in src/main/resources.  For the JAX-RS project (or any WAR project) the file goes in to the WEB-INF directory.  In an Eclipse Maven project, this folder can be found in src/main/webapp.  The file can be left empty, but I like to add the basic CDI XML which is:


Annotating the JAX-RS Resource


The next step is to add the CDI @Inject annotation to the JAX-RS resource.  For example, lets assume we have a simple EJB that provides a single method that returns a String that represents a message.  The EJB interface and implementation may look something like this:



The EJB can then be injected into the JAX-RS resource using the @Inject annotation.  Lets assume the JAX-RS resource look like this:


Build and deploy the code to Liberty and at runtime, CDI will retrieve the EJB from JNDI and inject the EJB into the resource after it's created.

1 comment:

  1. Thank you, this solved my problem! I had an application that was giving me a headache with Injection and after reading this article I realized they put the beans.xml for the JAX-RS project in the META-INF folder instead of the WEB-INF. Once I moved it to the right place all started working!

    ReplyDelete