CDI (Contexts and Dependency Injection) is the standard DI framework in Java EE. Since version 6 it has been part of the specification and finally delivers what Spring has had for years — type-safe dependency injection with annotations.
CDI basics¶
@Inject instead of new. The container manages object lifecycle and resolves dependencies automatically. No XML configuration — CDI uses annotations and convention. Every class with a beans.xml in META-INF/WEB-INF is a CDI bean.
Scopes¶
@RequestScoped — new object per HTTP request. @SessionScoped — per HTTP session. @ApplicationScoped — singleton. @ConversationScoped — explicitly managed scope across multiple requests. @Dependent — default, new object at every injection point. Choosing the right scope is critical for correct behavior and performance.
Producers¶
@Produces methods create objects that the CDI container cannot produce automatically (EntityManager, configuration values, external resources). An alternative to the factory pattern — cleaner and more declarative.
Interceptors and Decorators¶
Interceptors for cross-cutting concerns: @Interceptor with @AroundInvoke for logging, security, caching. The @Transactional interceptor replaces EJB transactions. Decorators for extending business logic without modifying the original.
CDI vs. Spring DI¶
CDI: standard, part of Java EE, type-safe qualifiers. Spring: older, larger ecosystem, works without an app server. For Java EE projects: CDI. For Spring projects: Spring DI. Don’t mix both in the same application.
Conclusion¶
CDI is a mature DI framework. For Java EE projects it is the preferred choice — standard, type-safe and with excellent integration with EJB and JPA. Spring DI remains the better choice outside the Java EE container.
Need help with implementation?
Our experts can help with design, implementation, and operations. From architecture to production.
Contact us