We will look at an example to understand dependency injection. We will write a simple business service that talks to a data service. We will make the code testable and see how proper use of DI makes the code testable.
The following is the sequence of steps we will follow:
- Write a simple example of a business service talking to a data service. When a business service directly creates an instance of a data service, they are tightly coupled to one another. Unit testing will be difficult.
- Make code loosely coupled by moving the responsibility of creating the data service outside the business service.
- Bring in the Spring IoC container to instantiate the beans and wire them together.
- Explore the XML and Java configuration options that Spring provides.
- Explore Spring unit testing options.
- Write real unit tests using mocking.