Enterprise intermediate

JNDI Lookup vs CDI Injection

Replace fragile JNDI string lookups with type-safe CDI injection for container-managed resources.

✕ Java EE
public class OrderService {
    private DataSource ds;

    public void init() throws NamingException {
        InitialContext ctx = new InitialContext();
        ds = (DataSource) ctx.lookup(
            "java:comp/env/jdbc/OrderDB");
    }

    public List<Order> findAll()
            throws SQLException {
        try (Connection con = ds.getConnection()) {
            // query orders
        }
    }
}
✓ Jakarta EE 8+
@ApplicationScoped
public class OrderService {
    @Inject
    @Resource(name = "jdbc/OrderDB")
    DataSource ds;

    public List<Order> findAll()
            throws SQLException {
        try (Connection con = ds.getConnection()) {
            // query orders
        }
    }
}
🔒

Type-safe wiring

Injection errors are caught at deployment time, not at runtime via string lookups.

🗑️

No boilerplate

Eliminates InitialContext creation, JNDI name strings, and NamingException handling.

🧪

Testable

Dependencies are injected fields, easily replaced with mocks in unit tests.

Old Approach
JNDI Lookup
Modern Approach
CDI @Inject
Since JDK
11
Difficulty
intermediate
JNDI Lookup vs CDI Injection
Available

Widely available since Jakarta EE 8 / Java 11

The traditional JNDI pattern forces you to use string-based resource names, handle NamingException, and manage an InitialContext. CDI injection with @Inject (or @Resource for container resources) lets the container wire dependencies automatically. Typos become compile-time errors, and classes are easier to test because dependencies can be injected directly.

Share 𝕏 🦋 in