Spring Setter Injection


In Spring, the beans are managed by the core container : initialization, dependency injection and life cycle.

To configure Spring container, we can use either XML file or annotations.

The dependency injection (DI) is either performed via Setter injection or via Constructor injection.

In this example, we will see how to inject an object into another object using Setter injection.


1. Technologies used

  • Spring 3.2.8.RELEASE
  • Maven 3.0.5
  • Eclipse 4.4
  • JDK 1.7


2. Project structure

We create a simple Java project.



3. Spring dependencies


4. Spring beans

We will create two classes : Tutorial and Reader.

File : Tutorial

File : Reader


We can see that Reader class uses Tutorial class as attribute, so we say that Reader class has a dependency to Tutorial class.

We have defined Setter method in both classes :
– In Tutorial class : to inject a title value into title attribute.
– In Reader class : to inject an instance of Tutorial class into myTuto attribute.


5. Bean configuration file

We will use XML file to define and configure our two beans.

File : beans.xml


In tutorial bean,  we have initialized title property by  “Spring Setter Injection” value.

In reader bean, we have initialized myTuto property by  the tutorial bean.


6. Run It

We will load Spring IoC container, retrieve Reader instance and execute the printTutorialTitle() method.


Output :

I’m reading : Spring Setter Injection


Download  source code