Mastering Spring 5.0
上QQ阅读APP看书,第一时间看更新

Understanding dependency injection

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:

  1. 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.
  2. Make code loosely coupled by moving the responsibility of creating the data service outside the business service.
  3. Bring in the Spring IoC container to instantiate the beans and wire them together.
  4. Explore the XML and Java configuration options that Spring provides.
  5. Explore Spring unit testing options.
  6. Write real unit tests using mocking.