As the name implies, using setter method spring container will inject the dependencies.This technique is considered as the best approach for dependency injection.
For configuring spring in your eclipse ide please refer hello world example.
Dependency Injection via Setter method
1.Country.java:
This is simple pojo class having some attributes so here country has name and object of Capital class.
Create Country.java under package org.arpit.javapostsforlearning.Copy following content into Country.java.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
packageorg.arpit.javapostsforlearning;
publicclassCountry{
StringcountryName;
Capital capital;
publicStringgetCountryName(){
returncountryName;
}
publicvoidsetCountryName(StringcountryName){
this.countryName=countryName;
}
publicCapital getCapital(){
returncapital;
}
publicvoidsetCapital(Capital capital){
this.capital=capital;
}
}
2.Capital.java
This is also simple pojo class having one attribute called “capitalName”.
Create Capital.java under package org.arpit.javapostsforlearning.java.Above Country class contains object of this class.Copy following content into Capital.java
Here We have declared two beans with corresponding ids.
1.Class Country with id as “CountryBean”
2.Class Capital with id as “CapitalBean”
Property’s value tagis for assigning value to corresponding attribute. so In above xml file,we have assigned countryName attribute of Country class with value as india
1
2
3
<propertyname="Name Of Attribute"value="Value Of attribute to be assigned"/>
Property’s ref tagis for assigning reference to corresponding attribute. so In above xml file,we have assigned reference of Capital class to capital attribute of Country class.
1
2
3
<propertyname="Name Of Attribute"ref="id of referencing bean"/>
4.SetterMehtodMain.java
This class contains main function.Create SetterMethodMain.java under package org.arpit.javapostsforlearning.Copy following content into SetterMethodMain.java
System.out.println(capitalName+" is capital of "+countryName);
}
}
You can note here that we have used ClassPathXmlApplicationContext for getting bean here.There are various ways for getting beans.In hello world example we have used XmlBeanFactory for getting beans.
5.Run it
When you will run above application,you will get following as output.