JNDI Lookup vs CDI Injection
Replace fragile JNDI string lookups with type-safe CDI injection for container-managed resources.
Porównanie kodu
✕ 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
}
}
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
JNDI Lookup
Nowoczesne podejście
CDI @Inject
Od JDK
11
Poziom trudności
Średniozaawansowany
Wsparcie JDK
JNDI Lookup vs CDI Injection
Dostępne
Widely available since Jakarta EE 8 / Java 11
Jak to działa
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.
Powiązana dokumentacja