Java 9 Dependency Injection
上QQ阅读APP看书,第一时间看更新

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 fetchDataObj) {
this.fetchDataObj = fetchDataObj;
}

public Object generateBalanceSheet(){

List<Object[]> dataLst = fetchDataObj.fetchData();
return exportDataObj.exportData(dataLst);
}

}

For each dependency, you need to put separate setter methods. Since the dependencies are set through the setter method, the object or a framework which supplies the dependencies need to call the setter methods at an appropriate time to make sure dependencies are available before a client object starts using it.