Pages Navigation Menu

Coding is much easier than you think

Constructor injection in Spring – Example

 

 
Instead of using the setter methods to inject values to attributes, the constructor of a class can be used to inject the values from outside the class. This work again, is done through the spring metadata file , as is in the case of setter injection.

 
** UPDATE: Spring Complete tutorial now available here.
 

1. Create the POJO class into which values are to be injected using setter injection

 
File : SimpleConstructorInjection
 

package com.simpleCodeStuffs;

public class SimpleConstructorInjection {
public SimpleConstructorInjection(String message){
this.message=message;
}

private String message;

public void setMessage(String message){

this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}

 

Note : Unlike setter injection, a constructor has to be explicitly defined for the POJO in case of constructor injection. This is because, usually a default(no parameter) constructor is taken up. But since we will be passing a value to the constructor of this POJO to instantiate it, we require a constructor whose parameters match the set of values passed from the xml.

 

2 Define the metadata

 
The value for the attribute of the POJO is provided as<constructor-arg value=” ” /> thereby setting the values of these attributes through the constructor.
 
File : Beans.xml
 








 

The values are injected into the POJO through the constructor of these classes

 

3. Write the main class to place a call to this POJO

 
File : MainClass.java
 

package com.simpleCodeStuffs;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
SimpleConstructorInjection obj =
(SimpleConstructorInjection) context.getBean("simpleConstructorInjection");
obj.getMessage();
}

}

 

4. Run it

 
The output appears as :-

simpleConstructorInjOutput

 
download