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:


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

public class MainService {

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

And injecting it in a JAX-RS bean:


package com.wordpress.dwuysan;

import javax.inject.Inject;

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

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

    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)


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