tags:

views:

40

answers:

2

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,

+3  A: 

EJBs can't work without a container. The dependencies (@EJB) are injected if the beans are instantiated by the container. If you are the one instantiating them, it is your responsibility to set the dependencies.

Furthermore, you are trying to use a non-static variable from a a static method - this won't even compile.

Bozho
A: 

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 @Resource or the more specialized @EJB and @WebServiceRef annotations 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:

  1. Deploy your Session Bean in a Java EE container (like JBoss, GlassFish, WebLogic, etc)

  2. Lookup the remote EJB using explicitly its global JNDI name. The code will look like that:

    Foo foo = (Foo) new InitialContext().lookup("FooEJB");
    

A few additional remarks:

  • With EJB 3.0, the global JNDI name is container dependent so I can't tell you what it will be exactly (EJB 3.1 finally introduced "portable global JNDI names").
  • You'll need to set up the JNDI environment (which is container dependent) for the lookup either by providing a jndi.properties on the class path or by using the InitialContext(Hashtable) constructor.
  • You'll need to provide the application server "client library" on the class path of the client (which is obviously specific to each product).

Search for previous questions or open a new one if you need more specific guidance.

Pascal Thivent