Dependency Injection
Any Java class we write depends on other classes. The other classes a class depends on are its dependencies. If a class directly creates instances of dependencies, a tight coupling is established between them. With Spring, the responsibility of creating and wiring objects is taken over by a new component called the IoC container. Classes define dependencies and the Spring Inversion of Control (IoC) container creates objects and wires the dependencies together. This revolutionary concept, where the control of creating and wiring dependencies is taken over by the container, is famously called IoC or dependency injection (DI).
In this chapter, we start with exploring the need for DI. We use a simple example to illustrate the use of DI. We will understand the important advantages of DI--easier maintainability, less coupling and improved testability. We will explore the DI options in Spring. We will end the chapter by looking at the standard DI specification for Java Contexts and Dependency Injection (CDI) and how Spring supports it.
This chapter will answer the following questions:
- What is dependency injection?
- How does proper use of dependency injection make applications testable?
- How does Spring implement DI with annotations?
- What is a component scan?
- What is the difference between Java and XML application contexts?
- How do you create unit tests for Spring contexts?
- How does mocking make unit testing simpler?
- What are the different bean scopes?
- What is CDI and how does Spring support CDI?