上QQ阅读APP看书,第一时间看更新
Constructor-based DI
Constructor-based DI is a design pattern to resolve the dependencies of a dependent object. In a constructor-based DI, a constructor is used to inject a dependent object. It is accomplished when the container invokes a constructor with a number of arguments.
Let's look at the following example for a constructor-based DI. In the following code, we show how to use a constructor for injecting a CustomerService object in a BankingService class:
@Component
public class BankingService {
private CustomerService customerService;
// Constructor based Dependency Injection
@Autowired
public BankingService(CustomerService customerService) {
this.customerService = customerService;
}
public void showCustomerAccountBalance() {
customerService.showCustomerAccountBalance();
}
}
The following is the content of another dependent class file, CustomerServiceImpl.java:
public class CustomerServiceImpl implements CustomerService {
@Override
public void showCustomerAccountBalance() {
System.out.println("This is call customer services");
}
}
The content for the CustomerService.java interface is as follows:
public interface CustomerService {
public void showCustomerAccountBalance();
}