CDI (Contexts and Dependency Injection) is one of the most essential and powerful APIs in Java EE. With CDI, you can easily divide your application into separate components interacting with each other, avoiding all the hassles of managing your components, life cycles, calling JNDI, and any other redundant programmatic work. Although the initial goal of CDI was to provide an easy mechanism for tying the web layer to the data access layer, CDI now has a broader scope of usage and implementation scenarios. Let's take an overview of the key features that CDI provides to our middleware solution:
DI (Dependency Injection): A popular technique for supplying components with other components they depend on. CDI provides a declarative approach for defining components and their scope of life, and of course obtaining them back. Moreover, DI in Java EE is used to easily retrieve essential platform components such as data sources, entity managers, enterprise Java beans, messaging destinations, and more.
Interceptors: Interceptors provide a simple mechanism for handling cross-cutting concerns in enterprise applications. Interceptors are methods that can be forced to precede the call to a set of other methods, in order to perform pre and/or post operations that are common among them, such as logging, transaction management, and more. This technique is commonly referred to by the term aspect-oriented programming.
Event Handling: Events are incidents that occur in our application, where one or more different objects are interested to react to. CDI provides a model for publishing events, where other objects can subscribe to those events.
In this chapter, we will learn about the amazing features that CDI provides to your applications, including:
Creating and using CDI beans
Providing different implementations to your bean
Understanding and using bean scopes
Injecting beans in other components in different ways
Understanding and using producers, interceptors, and events