Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java 9 Dependency Injection

You're reading from   Java 9 Dependency Injection Write loosely coupled code with Spring 5 and Guice

Arrow left icon
Product type Paperback
Published in Apr 2018
Publisher Packt
ISBN-13 9781788296250
Length 246 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Nilang Patel Nilang Patel
Author Profile Icon Nilang Patel
Nilang Patel
Krunal Patel Krunal Patel
Author Profile Icon Krunal Patel
Krunal Patel
Arrow right icon
View More author details
Toc

Dependency injection

 DI is one of the ways to invert the object creation process from your module to other code or entity. The term injection refers to the process of passing the dependent object into a software component.

Since DI is one of the ways to implement IoC, it relies on abstraction to set the dependency. The client object doesn't know which class will be used to provide functionality at compile time. The dependency will be resolved at runtime.

A dependent object does not directly call to the client object; instead, the client object will call a dependent object whenever required. It's similar to the Hollywood principle: Don't call us, we'll call you when we need to.

Dependency injection types

In DI, you need to set the entry point in a client object from which the dependency can be injected. Based on these entry points, DI can be implemented with the following types:

  • Constructor injection
  • Setter injection
  • Interface injection

Constructor injection

This is the most common way to inject dependency. In this approach, you need to pass the dependent object through a public constructor of a client object. Please note that in case of construction injection, you need to pass all the dependency objects in the constructor of a client object.

Constructor injection can control the order of instantiation and consequently reduce the risk of circular dependency. All mandatory dependencies can be passed through constructor injection.

In our BalanceSheet example, we need to pass two objects in a constructor, because it has two dependencies: one is for fetch data, and the second is for export data types, as per the following snippet:

public class BalanceSheet {

private IExportData exportDataObj= null;
private IFetchData fetchDataObj= null;

//All dependencies are injected from client's constructor
BalanceSheet(IFetchData fetchData, IExportData exportData){
this.fetchDataObj = fetchData;
this.exportDataObj = exportData;
}

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

All dependencies are injected from a constructor of a client object. Since constructors are called only once, it's clear that the dependency object will not be changed until the existence of a client object. If a client uses constructor injection, then extending and overriding it would be difficult sometimes.

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.

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.

You have been reading a chapter from
Java 9 Dependency Injection
Published in: Apr 2018
Publisher: Packt
ISBN-13: 9781788296250
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime