O'Reilly logo

Hands-On High Performance with Spring 5 by Dinesh Radadiya, Prashant Goswami, Pritesh Shah, Subhash Shah, Chintan Mehta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

@Componentpublic class BankingService {  private CustomerService customerService;  // Constructor based Dependency Injection  @Autowired  public BankingService(CustomerService customerService) {    this.customerService = customerService;  }  public void showCustomerAccountBalance() { customerService.showCustomerAccountBalance(); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required