Why do I have to lookup an EJB stub per JNDI if it is already in the client class path?
I'm confused about the use of JNDI to lookup EJB stubs. If I have an application server that doesn't dynamically download stubs and thus I have the stubs on the client classpath, then what is the purpose of my client looking up those stubs with JNDI?
For example:
InitialContext ctx=new InitialContext();
SomeEJBHome stub=ctx.lookup("someEJB");
Here I get back a stub, which I already have in my classpath. It was given to be via client.开发者_开发问答jar or what have you. Why am I looking up that stub if I already have it?
This works out of the box if your EJB client (the caller, i.e. web application) and the EJBs reside in the same EAR (JVM cluster, etc.). If you have different EARs, one containg your web client and another one containg your EJBs you must make the client stubs available to the client EAR (eclipse project type EJB Client) typically by using a JAR file.
Then why am i looking up that stub if i already have it? You have to look up the stub because an EJB is an Object managed by the Java EE container, so you can't simply instantiate it. If you look it up you retrive an object created by the container.
BTW: If you use Java EE 6 you can get rid of this stuff, use Dependency Injection instead.
The client stubs implement the client to the remote interface, but they do not know where to connect to. The following lines define the context your client uses to connect to the EJB container. In case of a remote client you must specify the different attributes like hostname and port so that the context knows from where to retrieve the reference to your remote EJB.
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, <NamingContextFactory>);
env.put(Context.PROVIDER_URL, <url:port>);
env.put(... container specific props);
InitialContext ctx = new InitialContext(env);
The following call tries to find the EJB at the remote location provided above:
SomeEJBHome stub = ctx.lookup("someEJB");
精彩评论