Search code examples
javajsfjakarta-eeejbpojo

Using EJB injection in a POJO


I know that injection using the @EJB annotation is only possible in an EJB class, a servlet, or a JSF managed bean, but in the same time I need to have an instance of a some injected business interface in a POJO class, so I thought of doing the following:

in my JSF managed bean

@EJB BusinessInterfaceLocal businessInterface;

private void someMethod(){
    PojoInterface pojo = new PojoClass(this.businessInterface);
}

and in my POJO class I have this constructor

BusinessInterfaceLocal businessInterface;    

public PojoClass(BusinessInterfaceLocal businessInterface){
   this.businessInterface = businessInterface;

   //The following throws a Null Pointer Exception
   this.businessInterface.someMethodCall();
}

Shouldn't the above work correctly? but it doesn't, the businessInterface object at the PojoClass is evaluated to null, and thus throwing a null pointer exception.

I was hoping if anyone could point me out, on what I'm doing wrong.

Thanks in advance.


Solution

  • verification

    Is it possible you create the PojoClass before the EJB gets injected. By that I mean, where do you invoke "someMethod"? Is it in the constructor of the managed bean? A variable simply does not lose its referenced value.

    You said you could see the BusinessInterfaceLocalbean isn't null in the Managed bean, can you verify you create the Pojo after that check?

    Alternative solutions:

    solution 1 You can use the POJO as a stateless bean, I don't see any problems in doing that, unless of course you are trying to use the POJO outside of your EE container, which is, by the looks of it not the case.

    Making the POJO stateless would make you able to inject the EJB.

    solution 2 OR a JNDI lookup, implemented as followed:

    @Stateless(name="myEJB")
    public class MyEJB {
    
      public void ejbMethod() {
      // business logic
      }
    
    }
    
    public class TestEJB {
    
      public static void main() {
      MyEJB ejbRef = (MyEJB) new InitialContext().lookup("java:comp/env/myEJB");
      ejbRef.ejbMethod();
      }
    }