Java Reference
In-Depth Information
InitialContext lookup
Although both DI and lookup using EJBContext are relatively convenient, the problem
is that the EJBContext is available only inside the Java EE or application client contain-
er. For POJOs outside a container, you're limited to the most basic method of looking up
JNDI references—using a JNDI InitialContext . The code to do this is a little mech-
anical, but it isn't too complex:
Context context = new InitialContext();
BidService bidService = (BidService)
context.lookup("java:app/ejb/DefaultBidService");
...
bidService.addBid(bid);
The InitialContext object can be created by any code having access to the JNDI API.
Also, the object can be used to connect to a remote JNDI server, not just a local one. Note
that although this code probably looks harmless enough, you should avoid it if at all pos-
sible. Mechanical JNDI lookup code was one of the major pieces of avoidable complexity
in EJB 2, particularly when these same bits of code were repeated hundreds of times across
an application.
5.2.10. When to use JNDI lookups
For the majority of cases, the @EJB and @Resource annotations will be able to inject
the resources you need into your classes and you'll not need to use JNDI lookups directly.
There are, however, cases when JNDI lookups will be needed.
Classes not managed by the container will need to use JNDI lookups. The @EJB and @Re-
source annotations are available only to classes managed by the Java EE or application
client container. This includes objects like EJBs, MDBs, Servlets, and JSF-backing beans.
Any nonmanaged class will need to use JNDI lookups through the InitialContext to
get access to the server's resources.
Resource access isn't always static, and as a consequence, it may not be possible to
use the @EJB or @Resource annotations to inject a static resource into your object. If
your resource lookup is dynamic, you'll need to use JNDI lookups. If this dynamic be-
havior occurs in a container-managed resource such as an EJB, you're able to inject an
EJBContext into your EJB (using @Resource , of course) and then use EJBCon-
Search WWH ::




Custom Search