Spring Constructor Injection

 

In this example, we will see how to perform Spring dependency injection via constructor.

We will resume the Spring Setter Injection example, but this time we will use Constructor Injection.

We will configure Spring IOC container using XML file : beans.xml

 

1. Technologies used

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

 

2. Project structure

Spring-Constructor-Injection

 

3. Spring dependencies

 

4. Spring beans

Here are our two classes : Tutorial and Reader.

File : Tutorial

File : Reader

 

In the Reader class constructor, we have the myTuro argument that represents a dependency on the Tutorial class.

In this case, the constructor injection is performed when Spring IOC container invokes the Reader class constructor.

 

5. Bean configuration file

We will configure our beans to initialize with passing arguments to the constructor.

File : beans.xml

 

So at application startup, Spring will use constructor-arg element to :
– initialize the tutorial bean by injecting "Spring Constructor Injection" value
– initialize the reader bean by injecting tutorial bean

 

6. Ambiguity

In some cases, there may be an ambiguity while passing arguments to the constructor.

 

In beans.xml file, if we use the following configuration :

the reader bean will be not initialized correctly, because Spring Container uses by default the first constructor that supports this configuration.

So we will have  :  reader [age:1122334455,  phoneNumber:30]

To resolve this, we can use the index attribute to specify explicitly the order of constructor arguments :

 

7. Run It

We load Spring container, get Reader instance and execute the printTutorialTitle() method.

 

Output :

I’m reading : Spring Constructor Injection

 

Download  source code