aspose file tools
The moose likes EJB and other Java EE Technologies and the fly likes EJB Injection and JNDI lookup ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "EJB Injection and JNDI lookup ?" Watch "EJB Injection and JNDI lookup ?" New topic

EJB Injection and JNDI lookup ?

Saeed Amer
Ranch Hand

Joined: Jan 20, 2004
Posts: 140
Hi there,

While reading through page# 416 of EJB Code spec (Section: EJB Reference Programming Interfaces), I came across an example which looks like this:

1 @EJB(name=�ejb/EmplRecord�, beanInterface=EmployeeRecordHome.class)
2 @Stateless public class EmployeeServiceBean
3 implements EmployeeService {
4 public void changePhoneNumber(...) {
5 ...
6 // Obtain the default initial JNDI context.
7 Context initCtx = new InitialContext();
8 // Look up the home interface of the EmployeeRecord
9 // enterprise bean in the environment.
10 Object result = initCtx.lookup("java:comp/env/ejb/EmplRecord");
11 // Convert the result to the proper type.
12 EmployeeRecordHome emplRecordHome = (EmployeeRecordHome)
13 javax.rmi.PortableRemoteObject.narrow(result,
14 EmployeeRecordHome.class);
15 ...
16 }
17 }

What I find puzzling here is that code is "injecting" EJB reference (line# 1) and then ALSO performing a JNDI Lookup (line# 10) - why? I thought we should be doing either of the two things and NOT both. Could someone shed some light on this, please? What am I missing here

Many thanks in advance!
Mark Spritzler

Joined: Feb 05, 2001
Posts: 17260

In that example I don't see the @EJB on an attribute of the class, and it is an interface anyway.

Injection is on attributes.


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Saeed Amer
Ranch Hand

Joined: Jan 20, 2004
Posts: 140
Thanks Mark but I am confused - what is the effect of Line#1 in the code?

Thanks again!
Edvins Reisons
Ranch Hand

Joined: Dec 11, 2006
Posts: 364
Line 1 is class-level (it comes before the class declaration) and gives you the JNDI entry to use to find the home reference by lookup() on Line 10. Notice that Line 1 does NOT give you an object reference.
Pratheep Nair

Joined: Sep 20, 2005
Posts: 14
Line#1 says that the JNDI name for the EJB is ejb/EmplRecord. However, you are doing the EJB lookup using the JNDI reference; hence you have the java:comp/env at the front. It is not mandatory to have the JNDI reference. However, it is a good practice. It helps to de-couple your code from deployment time configuration. If you lookup using the JNDI reference rather than by the actual JNDI name, even if the actual JNDI name changes, your code need not change. Ask more questions if you are still not clear...
I agree. Here's the link:
subject: EJB Injection and JNDI lookup ?