Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of Autowire by Constructor
Previous Home Next

Introduction: In the case of Autowire by constructor , in this approach type of parameter of the constructor are used to identified the bean to be injected in case of overloaded constructed has a maximum parameter will choose.

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="b" class="org.r4r.B" autowire="constructor"/>
</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:

 A is instantiated
Parameterized constructor of B is invoked.
Previous Home Next