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.
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.
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