< Prev
Next >



Dependency Injection with Constructor



In our last tutorial, we understood how to perform Dependency Injection using setter methods, in this tutorial we are going to understand about how to perform Dependency Injection using constructor, within a Spring Project.


To understand this concept of Dependency Injection by the constructor, let's proceed with an example. In the upcoming section, we are going to create a few loosely coupled Java classes also known as beans, configure these beans in a configuration xml file, load and instantiate the beans and perform dependency injection using the Spring Framework.




Creating the Java class - OutdoorSport


We are going to create a java class named OutdoorSport within the decodejava package and this class contains a message info().

package decodejava;

public class OutdoorSport
{
	
	public void info() 
	{
		System.out.println("-An Outdoor Sport-");	
	}

}





Dependent class with an OutdoorSport object - Tennis


Next, we are going to add another Java class named Tennis and it is going to contain a String object and an OutdoorSport reference, hence Tennis class is dependent on OutdoorSport class.

These objects of String class and the OutdoorSport class will be injected into a Tennis instance/bean by an automatic call to the setter methods in the Tennis class by the Spring Container, when the Tennis bean is created by it using the configuration xml file(to be created in the upcoming section).


package decodejava;

public class Tennis 
{

	OutdoorSport sport;
	String message;
	
	
	//Constructor to set the String object and the OutdoorSport object.
	public Tennis(OutdoorSport sport, String message)
	{
		this.sport = sport;
		this.message = message;
	}

	
	//method to get the String object
	public void getMessage()
	{
		System.out.println("Message is : " + message);
	}
	
	
	//method to get the OutdoorSport object
	public OutdoorSport getSport()
	{
		return sport;
	}
}





Adding the Utility class that calls the Spring API


Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2