Injecting EJB into a JAX-RS

Following my previous post here, I tried to inject an EJB 3.1 stateless session bean into this resource, only to find the infamous java.lang.NullPointerException.

Supposed you have an EJB as follows:

MainService

package com.wordpress.dwuysan.service;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;

@Stateless
@LocalBean
public class MainService {

    public String sayHello(final String name) {
        return "Hello" + name;
    }
}

And injecting it in a JAX-RS bean:

GenericResource

package com.wordpress.dwuysan;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path(value = "generic")
public class GenericResource {

    @Inject
    private com.wordpress.dwuysan.service.MainService mainService;

    @GET
    public String get() {
        return this.mainService.sayHello("test");
    }
}

This will result in java.lang.NullPointerException.

To fix this, the JAX-RS bean must also be “managed”, so simply add the annotation javax.annotation.ManagedBean to your JAX-RS bean (Nelson 2011)

References:

Nelson, L, 2011, ‘How do I inject a local stateless session bean into a JAX-RS resource using CDI?’, accessed 06 December 2012.

Advertisements