I am trying to inject an EJB with the @EJB annotation :
- when I inject an EJB into another EJB it works fine.
- when I inject the same EJB into a servlet I got a null pointer exception (my EJB is null).
myapp.ear contains the following :
- myapp.war (where the servlet is located)
- myapp.jar (where the EJBs are)
EJB Interface :
package com.mycompany.myapp.ejb.hello;
@Local
public interface HelloEjb {
public final static String NAME = "HelloEjb";
public String sayHello();
}
EJB Impl :
package com.mycompany.myapp.ejb.hello;
@Stateless(name = HelloEjb.NAME)
public class HelloEjbImpl implements HelloEjb {
@Override
public String sayHello() {
return "Hello";
}
}
My Servlet :
public class HelloServlet extends HttpServlet {
@EJB
private HelloEjb helloEjb;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("This is my stateless session-EJB: " + helloEjb.sayHello());
out.println("</html>");
out.close();
}
}
The web.xml in the WAR has nothing spetacular, only the servlet defintion, no ejb tags :
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="MyApp" version="2.5"
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/web-app_2_5.xsd">
<!-- General -->
<display-name>My App</display-name>
<!-- Standard Action Servlet Configuration -->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.mycompany.myapp.web.servlet.HelloServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- The Usual Welcome File List -->
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
If in the servlet I use lookup, it works I am able to get the EJB :
helloEjb = ctx.lookup("ejblocal:com.mycompany.myapp.ejb.hello.HelloEjb");
I am using Websphere 7 & EJB 3.0
Any help would be much appreciated.
My first shot is, if you specifiy a ‘name’ for your stateless EJB you should inject it with ‘mappedName’ attribute eg. ‘@EJB(mappedName=”foo.FooRemote”)’