Advertisement



< Prev
Next >



Dependency Injection with Setter Methods



Today we are going to understand about one of the main features of Spring Framework - Dependency Injection and how to use this feature within a Spring Project using the Eclipse Integrated Development Environment(IDE) application.


Dependency Injection is a feature of Spring Framework which allows us inject primitive values as well as an object(bean) value into another object(bean). In dependency injection, a dependency could be a primitive value or an object(bean). An injection is the passing of a such dependency(primitive value or an object) to a dependent object that would use it.


To understand this concept of dependency Injection by the setter method, 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;


	public void getMessage() 
	{
		System.out.println("Message is : " + message);
		sport.info();
	}

	
	//Setter method to set the message
	public void setMessage(String message) 
	{
		this.message = message;
	}
	
	
	//Setter method to set the OutdoorSport object
	public void setSport(OutdoorSport sport)
	{
		this.sport = sport;
	}
	
}



Advertisement




Adding the Utility class that calls the Spring API


Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement