ejb@glassfish.java.net

Re: How to lookup a Local/Remote EJB from a servlet? (ie. Local/Remote EJB access, without the @EJB annotation)

From: Kenneth Saks <Kenneth.Saks_at_Sun.COM>
Date: Tue, 28 Oct 2008 12:07:32 -0400

On Oct 28, 2008, at 11:52 AM, Drayton Brown wrote:

> Hi
>
> I'm trying to implement a EJB factory for BlazeDS, an update to this
> library: http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&loc=en_us&extid=1089970
>
> This requires that I be able to dynamically instanciate an EJB. In
> the library above this is done like this:
>
> Context ctx = new InitialContext();
> Object res = ctx.lookup( <EJB Name> );
>
> Unfortunately, this does not seem to work anymore. I believe this is
> due to some changes in the servlet specification. (Apparently it
> worked with servlet 2.4, but it doesn't with 2.5).
>
> At the moment my application only allows direct injection of EJBs
> via the @EJB annotation, which is not useful at all for what I want
> to do.
Hi Drayton,

If you already have an @EJB annotation it's very easy to lookup the
same EJB dependency. Just add
a name() attribute to the @EJB , e.g. @EJB(name="fooref"). Then,
wherever in the code you want to lookup
an EJB add :
         Object res = ctx.lookup("java:comp/env/fooref");

Note that the portion of the name relative to java:comp/env/ is the
value of the name() attribute in @EJB.
In addition to allowing for injection, the @EJB annotation serves the
same purpose as an ejb-ref or
ejb-local-ref in web.xml. It defines an environment entry within the
web application's component environment.


More on this in our EJB FAQ :

https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html#POJOLocalEJB
https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html#EJB_ejb-
ref_ejb_local_ref

  --ken

>
>
> I would prefer to do this using a local EJB, but if all else fails,
> I am open to switching to remote EJBs.
>
> Your help is greatly appreciated so, thanks in advance!
>
> Regards
> Drayton