Chapter 3. Dependency Injection

 

This chapter covers

  • Inversion of Control (IoC) and Dependency Injection (DI)
  • Why DI is an important technique to master
  • How JSR-330 united DI for Java
  • Common JSR-330 annotations such as @Inject
  • Guice 3, the reference implementation (RI) for JSR-330

Dependency Injection (a form of Inversion of Control) is an important programming paradigm that has become part of mainstream Java development since about 2004. In short, DI is a technique in which your object gets its dependencies given to it, as opposed to having to construct them itself. There are many benefits to using DI—it makes your codebase loosely coupled, easier to test, and easier to read.

This chapter begins by cementing your knowledge of DI theory and the benefits that it brings to your codebase. Even if you already work with an IoC/DI framework, there’s material in this chapter that will give you a deeper understanding of what DI is truly about. This is especially important if (like many of us) you started working with DI frameworks before you had a real chance to fully explore the reasoning behind them.

You’ll learn about JSR-330, the official standard for DI in Java, which will give you the behind-the-scenes understanding of the standard set of DI annotations for Java. Following on from that, we’ll introduce the Guice 3 framework, which is the reference implementation (RI) for JSR-330 and is also considered by many to be a nice, lightweight approach for DI in Java.

3.1. Inject some knowledge—understanding IoC and DI

3.2. Standardized DI in Java

3.3. Guice 3—the reference implementation for DI in Java

3.4. Summary