Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of Autowire by Name
Previous Home Next

Introduction: In the case of Autowire by Name, The IOC container uses the name of a bean property to fined out the bean for injecting i.e in this approach the configuration bean to be used for satisfied the dependency of the bean must have the same bean property.

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="a" class="org.r4r.A"/>
<bean id="y" class="org.r4r.A"/>
<bean id="b" class="org.r4r.B" autowire="byName"/>
</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;
A y;
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 typeName a.");
}
public void setY(A y) {
this.y = y;
System.out.println("setA() method is invoked typeName y.");
}
}

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
A is instantiated
setA() method is invoked typeName a.
setA() method is invoked typeName y.
Previous Home Next