Dependency Injection via Setter method in spring

  1. This is 6 of 16 parts of tutorial series

Tutorial Content: Spring tutorial for beginners

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

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.

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

3.SetterMehtodMain.java

This class contains main function.Create SetterMethodMain.java under package org.arpit.javapostsforlearning.Copy following content into SetterMethodMain.java
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.

4.ApplicationContext.xml


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 tag is for assigning value to corresponding attribute. so In above xml file,we have assigned countryName attribute of Country class with value as india

Property’s ref tag is for assigning reference to corresponding attribute. so In above xml file,we have assigned reference of Capital class to capital attribute of Country class.

5.Run it

When you will run above application,you will get following as output.
 

Source code:

In next post,we will see dependency injection via constructor

Add Comment