See also: EJB Naming Service, Location Transparency for EJB-specific usage.
In a distributed system, how do clients locate resources like databases, EJB components, or other services? Hard-coding connection details (like IP addresses) is bad practice — we need a centralized naming service that can change without recompiling code.
JNDI is a Java API that provides a unified interface for locating resources (objects, services) through a naming and directory service. It allows clients to look up resources by logical name rather than physical location, providing location independence and flexibility.
- Resource (database, EJB, etc.) is bound to JNDI with a logical name
- Client creates InitialContext
- Client calls ctx.lookup(“logicalName”) to get the resource
- JNDI communicates with underlying Service Provider
- Service Provider (LDAP, DNS, RMI Registry, etc.) resolves the name
- Client gets reference to resource
Common JNDI trees:
- java:comp/env — application environment
- jdbc/ — database connections
- ejb/ — EJB references
- Location independence: Change resource location without changing client code
- Decoupling: Client doesn’t need to know implementation details
- Centralized: All resources registered in one place
- Generic: Works with many backends (RMI, LDAP, CORBA, etc.)
- Hierarchical: Supports nested contexts (java:comp/env/jdbc)
- Dependency injection: Can inject JNDI references automatically (EJB 3.x)
- Built from: Naming Service — core naming concept, EJB Naming Service (EJB-specific usage)
- Related: Directory Service — adds attributes to naming
- Builds into: EJB Container — EJB container registers beans in JNDI, Location Transparency (JNDI enables location-independent lookups)
- Builds into: Home Interface (what clients look up via JNDI), EJB Development Lifecycle (step 5+: deploy, then JNDI lookup)
- Contrasts with: RMI Registry — RMI Registry is a specific JNDI provider, Hard-coded addresses (JNDI is registry-based, not address-based)
- Related: JMS Programming Model, JMS, CMP Abstract Accessors, One-to-Many Relationship, Distributed Objects (clients access objects via JNDI)
- Multiple InitialContexts in same application can be confusing
- Different servers use different JNDI trees
- JNDI lookups have performance cost
- In EJB 3.x, @EJB annotation often replaces manual lookup
- Security: Ensure JNDI tree is properly configured in production