Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of Setter Injection
Previous Home Next

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

Technology use to run this source code

  1. Spring 2.5
  2. Eclipse
  3. JDK 1.6

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="a1" class="org.r4r.A"/>
<bean id="a2" class="org.r4r.A">
<constructor-arg value="10"/>
</bean>
<bean id="a3" class="org.r4r.A">
<property name="a" value="100"/>
</bean>
</beans>

A.java

package org.r4r;
public class A {
int a;
public A(int a) {
super();
this.a = a;
System.out.println("A is instantiated using parameter constructor.");
System.out.println("Value of a:-\t"+a);
}
public A() {
super();
System.out.println("A is instantiated using Default constructor.");
}
public void setA(int a) {
this.a = a;
System.out.println("Value of A is set by setA() method.");
System.out.println("Value of a:-\t"+a);
}
}

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[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
//A a1=(A)f.getBean("a1");
@SuppressWarnings("unused")
A a2=(A)f.getBean("a2");
@SuppressWarnings("unused")
A a3=(A)f.getBean("a3");
}
}

Output:

 A is instantiated using parameter constructor.
Value of a:- 10
A is instantiated using Default constructor.
Value of A is set by setA() method.
Value of a:- 100
Previous Home Next