Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of Constructor Injection
Previous Home Next

Introduction:In the dependency injection satisfied the dependency of an object through the constructor dependency injection. Following this example inject the dependency using the constructor.

Technology use to run this source code
  1. Spring 2.5
  2. Eclipse
  3. JDK 1.6

Source Code

applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="ab" class="org.r4r.A">
<constructor-arg value="101" />
<constructor-arg value="Mukund Singh" />
</bean>
</beans>

A.java

package org.r4r;
public class A {
int a;
String b;
public A(int a,String b) {
super();
this.a=a;
this.b =b;
System.out.println("Constructor is invoked");
}
public void display() {
System.out.println(a+"\t\t"+b);
}
}

Test.java

package org.r4r;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String ar[]){
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
System.out.println("Constructor value are following");
A a1=(A)f.getBean("ab");
a1.display();
}
}

Output:

Constructor value are following
Constructor is invoked
101 Mukund Singh
Previous Home Next