Search code examples
glassfish-3java-ee-6cdi

@EJB and @Inject both causing NPE in Glassfish 3.1.2 and Java 6


I'm deploying a Maven WebApp created with NetBeans 3.1.2 on Mac using lastest JDK 6 and Glassfish 3.1.2

It contains a basic JAX-RS service. I tried inject both a SLSB (with @EJB) and a CDI managed bean (@Inject) into it. In both cases I hit NPE.

SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container java.lang.NullPointerException at com.mycompany.common.jee6.glassfish3.webapp.GenericResource.getXml(GenericResource.java:47) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597)

To save on ink the project is uploaded here

https://bitbucket.org/DessieK/jee6-cdi-webapp/src


Solution

  • Make your JAX-RS service a stateless session bean:

    @Path("generic")
    @Stateless // <- It's an EJB
    public class GenericResource {
        @EJB
        NewSessionBean nsb;
    
        @GET
        @Produces("application/xml")
        public String getXml() {
            nsb.helloWorld();
            return "<hello>World</hello>";
        }
    }