• ↑↓ pour naviguer
  • pour ouvrir
  • pour sélectionner
  • ⌘ ⌥ ↵ pour ouvrir dans un panneau
  • ←→ pour naviguer
  • esc pour rejeter
⌘ '
raccourcis clavier

See also: EJB Naming Service, Location Transparency for EJB-specific usage.

The Problem

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.

Core Idea

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.

How It Works

  1. Resource (database, EJB, etc.) is bound to JNDI with a logical name
  2. Client creates InitialContext
  3. Client calls ctx.lookup(“logicalName”) to get the resource
  4. JNDI communicates with underlying Service Provider
  5. Service Provider (LDAP, DNS, RMI Registry, etc.) resolves the name
  6. Client gets reference to resource

Common JNDI trees:

  • java:comp/env — application environment
  • jdbc/ — database connections
  • ejb/ — EJB references

Visual Explanation

G Client Client InitialContext InitialContext Client->InitialContext lookup() Service Provider Service Provider InitialContext->Service Provider resolve name LDAP/RMI Registry/DNS LDAP/RMI Registry/DNS Service Provider->LDAP/RMI Registry/DNS Backend Resource Resource Service Provider->Resource returns reference

Key Properties

  • 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)

Connections

Edge Cases & Gotchas

  • 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