1 Why CDI?

CDI (Contexts and Dependency Injection) is a component model that was introduced for Java EE 6 in Version 1.0 and was updated to Version 1.1 in Java EE 7. The reference implementation is Weld from RedHat. For the purposes of this book, we will use Weld 2.2.6, which already supports CDI 1.2 and which our application server of choice, WildFly 8.2.0, already contains.

With regards to the content of this Cloud Tutorial, we should mention pre-emptively that readers hoping to get to implement new application functions will be disappointed. After completion of the tutorial, the provided sample application will function just as it did up until the beginning – nothing new will be added that will be visible to the user.

And wait – it gets worse! The entire application could be developed without using CDI at all. With this in mind, you’d be justified in asking why we’re even studying it!

The reason to doing so is that CDI allows us to write software components which are loosely coupled. Once an application gets beyond a certain size, it is essential to divide it into smaller maintainable and testable parts. This is like THE crucial factor for the long-term success of each application and loose coupling is the tool to achieve it.

Tight and Loose Coupling of Components

Application components consist of a number of classes. A class of a component A can directly import a class of another component B. This creates a strong dependency from component A to component B, since component A can only be used when component B is included in the classpath. This is referred to as the tight coupling of components and has the consequence that changes to component B often bring about changes to component A as well. If component B introduces an interface via which component A accesses the functionality of B, the dependency of the components is reduced. A change in component B must ensure only that the interface does not change; there is no need to change component A. This is known as a loose coupling of components.

The dependency of components can be further reduced by enabling them to send and receive only these well-defined messages amongst each other. If a component is updated, the format of the message must be downward compatible in order to ensure that no changes to the receiving components are necessary.

For a further motivation why to use CDI it is helpful to have a look at the provided sample application first. So we get back to answer the ‘Why CDI’ question in Section 2.3, where we will criticise the provided sample application.

Further readings

Martin Fowler gives in Reducing Coupling some tips about how to decouple components in an application.


Use the message board below to give the authors your feedback or to discuss this page’s topic with other readers (in English please!). Please don’t expect the authors to answer directly, but they might update the content of this site according to your feedback.