Setter injection

As its name suggests, here dependency injection is done through setter methods exposed publicly. Any dependency not required at the time of client object instantiation is called optional dependency. They can be set at a later stage after a client object is created.

Setter injection is a perfect fit for optional or conditional dependency. Let's apply a setter injection to the BalanceSheet module.

The code would look as follows:

public class BalanceSheet {  private IExportData exportDataObj= null;  private IFetchData fetchDataObj= null;    //Setter injection for Export Data   public void setExportDataObj(IExportData exportDataObj) {    this.exportDataObj = exportDataObj;  }  //Setter injection for Fetch Data public void setFetchDataObj(IFetchData ...

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.