JNDI Lookup vs CDI Injection
Replace fragile JNDI string lookups with type-safe CDI injection for container-managed resources.
Code Comparison
✕ 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
}
}
}
Why the modern way wins
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
JDK Support
JNDI Lookup vs CDI Injection
Available
Widely available since Jakarta EE 8 / Java 11
How it works
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.
Related Documentation