I’ve got a NullPointerException using EJB3 in a J2SE environment (without EJB3 container)
Briefly, I’ve got a stateless bean implementing an interface.
When I call it in another class like in a main, a NullPointerException is triggered.
Sample:
@stateless
@Local(IMyInterface.class)
public class myBean implements IMyInterface{...}
public class Main{
@EJB
IMyInterface myInterface;
public static void main(String[] args){
Result result = myInterface.myBeanMethod(); // Exception happens here
}
}
I guess I miss some initialization stuff because the EJB is null when I first try to use it…
Thanks for your help,
While you can use JPA (which is part of EJB 3) “Entity Beans” (actually, POJOs) in a J2SE environment, you can’t use Session Beans without a container and you can’t benefit from injection of resources using the
@Resourceor the more specialized@EJBand@WebServiceRefannotations in a non-managed environment, i.e. a container. In other words, only managed components support injection (Servlets, JSF Managed beans, EJB components, etc).So, in your case, you’ll need to:
Deploy your Session Bean in a Java EE container (like JBoss, GlassFish, WebLogic, etc)
Lookup the remote EJB using explicitly its global JNDI name. The code will look like that:
A few additional remarks:
JNDIname is container dependent so I can’t tell you what it will be exactly (EJB 3.1 finally introduced “portable globalJNDInames“).jndi.propertieson the class path or by using theInitialContext(Hashtable)constructor.Search for previous questions or open a new one if you need more specific guidance.