users@glassfish.java.net

Re: null pointer in ejb

From: Sahoo <Sahoo_at_Sun.COM>
Date: Tue, 05 Feb 2008 11:15:15 +0530

That NPE is expected, because injection does not happen for arbitrary
instances - it only happens for instances created by the container, e.g.
servlets, EJBs, web filters, etc. "Table EE 5-1" in Java EE 5 platform
spec lists the classes for which injection happens.

Thanks,
Sahoo

Angelo Chen wrote:
> Hi,
>
> I have a servlet which calls a session EJB, the server is Glassfish v2:
>
> @Remote
> public interface HelloRemote {
> public String sayHi();
> }
>
> @Stateless(mappedName = "HelloFEJB")
> public class HelloFBean implements HelloRemote{
> public HelloFBean() {
> }
>
> public String sayHi() {
> return "Hi and Hello";
> }
> }
>
> when the EJB is injected in the servlet class(Hellow), everything works, but
> when the EJB is injected in another class(HelloEJBx), it has null pointer
> exception, like below, why?
>
> Thanks
>
> public class Hellow extends HttpServlet {
>
> ... some methods
>
> private String EJB_Hi() {
> HelloEJBx ejb = new HelloEJBx();
> return ejb.sayHi();
> }
>
> @EJB
> private HelloRemote hello = null;
> private String EJB_Hi2() {
> return hello.sayHi();
> }
>
> protected void processRequest(HttpServletRequest request,
> HttpServletResponse response)
> throws ServletException, IOException {
> String hi = EJB_Hi2(); // this works
> // String hi = EJB_Hi(); // this has null pointer at hello.sayHi() line
> private class below
> }
>
> private class HelloEJBx {
> @EJB
> private HelloRemote hello = null;
> public String sayHi() {
> return hello.sayHi();
> }
> }
>
> }
>
>
>