Spring Framework

Spring Projects

Spring Project 1

Dependency on objects example
Previous Home Next

Introduction:In the case of Dependency on object, The constructor-arg is the sub element of <bean ......> is used to specify the dependency of an object i.e to be satisfied the constructor-arg element uses reference of an attribute which are used to specify object respectively.

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="c1" class="org.r4r.Course">
<constructor-arg value="MCA"/>
<constructor-arg value="150000"/>
</bean>
<bean id="c2" class="org.r4r.Course">
<constructor-arg value="MBA"/>
<constructor-arg value="250000"/>
</bean>
<bean id="ab" class="org.r4r.Student">
<constructor-arg value="101"/>
<constructor-arg value="Mukund"/>
<constructor-arg>
<set>
<ref bean="c1"/>
<ref bean="c2"/>
</set>
</constructor-arg>
</bean>
</beans>

 

Course.java

package org.r4r;
public class Course {
String name;
int fee;
public Course(String name, int fee) {
super();
this.name = name;
this.fee = fee;
}
public String toString(){
StringBuffer b=new StringBuffer();
b.append(name).append("\t\t").append(fee);
return b.toString();
}
}

Student.java

package org.r4r;
import java.util.Iterator;
import java.util.Set;
public class Student {
int id;
String n;
Set<Course> course;
public Student(int id, String n, Set<Course> course) {
super();
this.id = id;
this.n = n;
this.course = course;
}
public String toString(){
StringBuffer b=new StringBuffer();
b.append("Name:").append(n).append("\n").append("Course details\n");
Iterator<Course> itr=course.iterator();
while(itr.hasNext()){
b.append(itr.next()).append("\n");
}
return b.toString();
}
}

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);
Student a1=(Student)f.getBean("ab");
System.out.println("Student information is,");
System.out.println(a1);
}
}

Output:

Student information is,
Name:Mukund
Course details
MCA 150000
MBA 250000
Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: