Jin Kwon
Jin Kwon

Reputation: 22025

@EJB not injected to JAX-RS

I have @LocalBeans and JAX-RS resources in different packages in a single ear.

And I also have a ServletFilter filtering before those resources.

I found that @EJB works for the ServletFilter but not for those resources.

@Stateless
@LocalBean
class MyBean { // in ejb jar
}

@WebFilter(urlPatterns = {"/*"})
class MyFilter implements Filter { // in the same war
    @EJB MyBean myBean; // not null
}

@ApplicationPath("/")
class MyApplication extends Application { // in the same war
}

@Path("/my")
class MyResource { // in the same war
    @EJB MyBean myBean; // null
}

No logs special, just an NPE in MyResource's method. Can anybody help me?

UPDATE -----------------------------------------------

Making those resource classes as @Stateless do works.

But I just curious that those ejb-jar and web-war are assembled into a single ear.

And then the web-war is a web component, isn't it?

UPDATE2 ------------------------------------------------------

Oh, I'm sorry. There is also MyApplication that makes MyResource as a JAX-RS resource.

When I deploy the ear GF detect it as an 'Enterprise Application'.

UPDATE3 ---------------------------------------------------------------

Here comes my application.xml

<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" version="6">
  <display-name>sngp-v0-ear</display-name>
  <module> <!-- EJBs are here -->
    <ejb>sngp-v0-beans-1.0-alpha-1-SNAPSHOT.jar</ejb>
  </module>
  <module>
    <web> <!-- JAX-RS are here -->
      <web-uri>sngp-v0-mobile-resources-1.0-alpha-1-SNAPSHOT.war</web-uri>
      <context-root>/sngp-v0-mobile-resources</context-root>
   </web>
  </module>
  <library-directory>lib</library-directory>
</application>

Upvotes: 2

Views: 3188

Answers (1)

perissf
perissf

Reputation: 16273

MyResource class isn't either a web component or an enterprise bean, but you are trying to inject an EJB into it. EJB injection is guaranteed to work only when the client is either a web component or another enterprise bean.

Try making MyResource @Stateless.

Have a look at this Java EE 6 tutorial regarding EJB injection. If you are using NetBeans, I have also found useful using the built-in wizard for creating RESTFul web services. Check out this link in case.

Upvotes: 3

Related Questions