Thursday, January 7, 2010

Constructor Injection using Spring

I wrote about Spring & Setter Injection in my previous blog now I am adding one more sample using constructor Injection. Constructor injection is almost same like setter injection except only difference that here IoC container initializes the constructor parameters.

Consider below sample java class.

Java Class:

import org.springframework.context.ApplicationContext;

public class TestConstructor {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"constructorinjection.xml"});
Inject inject = (Inject) context.getBean( "myInject" );
System.out.println( inject.getName() );

class Inject {

private String name;

public Inject(String name, String text)
{ = name + text;

public String getName() {

In above class constructor parameter values(name & text) would be injected from constructorinjection.xml configuration file.

Configuration file: constructorinjection.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

<bean id="myInject" class="Inject">
<constructor-arg type="java.lang.String" index="1">
<value>Welcome to example to constructor injection </value>
<constructor-arg type="java.lang.String" index="0">
<value>A text </value>

Here, </constructor-arg> has two optional attributes type and index. Type is not significant in this particular example but can be useful when using some other complex types. Specify type value based on your constructor type. Index is also one useful mechanism to be used within. Based on index value it assigns value to constructor parameter.

In above sampe output is:
A text Welcome to example to constructor injection

Now if you change index vaue 1 to 0 and 0 to 1 output is:
Welcome to example to constructor injection A text

If you have noticed I made one more change in this sample compare to my previous blog. I used ApplicationContext instead of BeanFactory. What is the difference? We will now see why ApplicationContext. The first thing you can notice is that you can (of course optionally) pass more than one XML bean definition/configuration files. Ultimately we are assigning the ApplicatioContetx instance to BeanFactory.

No comments:

Post a Comment