Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of Autowire by Type
Previous Home Next

Introduction: In case of autowiring by type , The IOC container used the bean property by type to identified the beans to be injected i.e in order to used autowiring by type we need to simply configure one bean for each property of the target bean.

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="x" class="org.r4r.A"/>
<bean id="b" class="org.r4r.B" autowire="byType"/>
</beans>

A.java

package org.r4r;
public class A {
public A() {
super();
System.out.println("A is instantiated");
}
}

B.java

package org.r4r;
public class B {
A a;
public B() {
super();
System.out.println("Default constructor of B is invoked.");
}
public B(A a) {
super();
this.a = a;
System.out.println("Parameterized constructor of B is invoked.");
}
public void setA(A a) {
this.a = a;
System.out.println("setA() method is invoked.");
}
}

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);
@SuppressWarnings("unused")
B b=(B)f.getBean("b");
}
}

output:

Default constructor of B is invoked.
A is instantiated
setA() method is invoked.
Previous Home Next