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
 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="simpleConstructorInjection" class="com.simpleCodeStuffs.SimpleConstructorInjection">
<constructor-arg value="SimpleCodeStuffs--Simple Constructor Injection"/>
</bean>
</beans>

 

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
 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.