- Building Microservices with Spring
- Dinesh Rajput Rajesh R V
- 362字
- 2021-07-02 14:54:05
With dependency injection pattern
The Factory idea avoids direct instantiation of an object of a class, and we also have to create another module that is responsible for wiring the dependencies between classes. This module is known as a dependency injector, and is based on the Inversion of Control (IoC) pattern. According to the IoC Framework, the Container it is responsible for object instantiation, and to resolve the dependencies among classes in the application. This module has its own life cycle of construction and destruction for the object defined under its scope.
In the following diagram, we have used the dependency injection pattern to resolve the dependencies of the TransferServiceImpl class:
In the following example, we have used an interface to resolve the dependencies:
Following is the TransferServiceImpl.java file:
package com.packt.patterninspring.chapter4.bankapp.service; public class TransferServiceImpl implements TransferService { AccountRepository accountRepository; TransferRepository transferRepository; public TransferServiceImpl(AccountRepository accountRepository,
TransferRepository transferRepository) { this.accountRepository = accountRepository; this.transferRepository = transferRepository; } @Override public void transferAmmount(Long a, Long b, Amount amount) { Account accountA = accountRepository.findByAccountId(a); Account accountB = accountRepository.findByAccountId(b); transferRepository.transfer(accountA, accountB, amount); } }
In the TransferServiceImpl class, we passed references of the AccountRepository and TransferRepository interfaces to the constructor. Now the TransferServiceImpl class is loosely coupled with the implementation repository class (use any flavor, either JDBC or JPA implementation of repository interfaces), and the framework is responsible for wiring the dependencies with the involved dependent class. Loose coupling offers us greater reusability, maintainability, and testability.
The Spring Framework implements the dependency injection pattern to resolve dependencies among the classes in a Spring application. Spring DI is based on the IoC concept, that is, the Spring Framework has a container where it creates, manages, and destructs the objects; it is known as a Spring IoC container. The objects lying within the Spring container are known as Spring beans. There are many ways to wire beans in a Spring application. Let's take a look at the three most common approaches for configuring the Spring container.
In the following section, we'll look at the types of the dependency injection pattern; you can configure the dependencies by using either one of them.