Interface injection
Interface injection defines a way by which the dependency provider should talk to a client. It abstracts the process of passing dependency. The dependency provider defines an interface that all clients need to implement. This method is not so frequently used.
Technically, interface injection and setter injection are the same. They both use some sort of method to inject dependency. However, for interface injection, the method is defined by objects which provide the dependency.
Let's apply interface injection to our balance sheet module:
public interface IFetchAndExport {
void setFetchData(IFetchData fetchData);
void setExportData(IExportData exportData);
}
//Client class implements interface
public class BalanceSheet implements IFetchAndExport {
private IExportData exportDataObj= null;
private IFetchData fetchDataObj= null;
//Implements the method of interface injection to set dependency
@Override
public void setFetchData(IFetchData fetchData) {
this.fetchDataObj = fetchData;
}
//Implements the method of interface injection to set dependency
@Override
public void setExportData(IExportData exportData) {
this.exportDataObj = exportData;
}
public Object generateBalanceSheet(){
List<Object[]> dataLst = fetchDataObj.fetchData();
return exportDataObj.exportData(dataLst);
}
}
We have created interface IFetchAndExport and defined methods to inject dependencies. The dependency provider class knows how to pass the dependency through this interface. Our client object (Balance Sheet module) implements this method to set dependencies.