ejb@glassfish.java.net

Re: EJB FAQ

From: Kenneth Saks <Kenneth.Saks_at_Sun.COM>
Date: Thu, 04 May 2006 13:16:32 -0400

Pavel Rábek wrote:

>Hello,
>I'm sending two follow-up questions for EJB FAQ.
>
>My first question concerning Local EJB Access:
>I'm able to get reference to Local interface of session bean through @EJB injection.
>But what about if I want to get this reference in run-time? (I mean some kind of lookup).
>
Hi Paul,

There are a number of options . First, any @EJB
declaration(field/method/ or class-level) can
*always* optionally be looked up via the component's private naming
context.

E.g.

private @EJB(name="myfooref") FooLocal fooLocal;

In addition to resulting in injection, this field-based @EJB also
declares an ejb-local-ref depedency within java:comp/env called
"myfooref".

So, it can be looked up as follows :

InitialContext ic = new InitialContext();
FooLocal fooLocal2 = (FooLocal) ic.lookup("java:comp/env/myfooref");

If the code doing the lookup is running within an ejb component, there
is an easier option because the EJBContext interface in EJB 3.0 has a
lookup method that is scoped directly to java:comp/env. So, you could do :

@Resource private SessionContext sessionCtx;
FooLocal fooLocal2 = sessionCtx.lookup("fooejbref");

That way, there's no need to use the JNDI api at all.

A third alternative is to simply declare the ejb-local-ref directly in
the deployment descriptor and look it up using either of the two
examples above. It looks just like an ejb-local-ref for a 2.x Local
interface, except you don't use a <local-home> element. Here's what
the @EJB above would look like translated into an ejb-local-ref in the
deployment descriptor (minus the injection-related elements)

<ejb-local-ref>
  <ejb-ref-name>fooejbref</ejb-ref-name>
   <ejb-ref-type>Session</ejb-ref-type>
   <local>com.acme.FooLocal</local>
</ejb-local-ref>

>
>
>My second question concerns EJB2 lookup:
>How can I use @EJB annotation to inject EJB2 session bean?
>
You just specify the Home or LocalHome instead of the Remote/Local
business interface.

E.g. for Remote 2.x interface pair SfulRemoteHome/SfulRemote, this
would look like

@EJB private SfulRemoteHome sfulRemoteHome;


After injection, the Home is available. No need to call
PortableRemoteObject.narrow() :-)

    SfulRemote sfulRemote = sfulRemoteHome.create( ... ) ;
     ...

>I'm able to lookup EJB2 bean via old style lookup but not via @EJB...
>
>Thanks,
>Paul
>
>---------------------------------------------------------------------
>To unsubscribe, e-mail: ejb-unsubscribe_at_glassfish.dev.java.net
>For additional commands, e-mail: ejb-help_at_glassfish.dev.java.net
>
>
>