Spring Framework

Spring Projects

Spring Project 1

Dependency on collection using Map example
Previous Home Next

Introduction:In the case of dependency on collection, constructor-arg is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the constructor-arg element uses MAP sub element to specify the dependency of MAP 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="ab" class="org.r4r.Institute">
<constructor-arg value="XYZ"/>
<constructor-arg>
<map>
<entry key="MCA" value="150000"/>
<entry key="MBA" value="250000"/>
<entry key="BCA" value="50000"/>
<entry key="BBA" value="100000"/>
</map>
</constructor-arg>
</bean>
</beans>

 

Institute.java

package org.r4r;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Institute {
String name;
Map<String, String> courseDetails;
public Institute(String name, Map<String, String> courseDetails) {
super();
this.name = name;
this.courseDetails = courseDetails;
}
public void display(){
System.out.println("Name:\t"+name);
System.out.println("Course Name\t\tFee");
Set<Map.Entry<String, String>> set=courseDetails.entrySet();
Iterator<Map.Entry<String, String>> itr=set.iterator();
while(itr.hasNext()){
Map.Entry<String, String> m=itr.next();
System.out.println(m.getKey()+"\t\t"+m.getValue());
}
}
}

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);
System.out.println("Constructor value are following");
Institute a1=(Institute)f.getBean("ab");
a1.display();
}
}

Output:

Constructor value are following
Name: XYZ
Course Name Fee
MCA 150000
MBA 250000
BCA 50000
BBA 100000
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: