Spring Framework

Spring Projects

Spring Project 1

Setter Injection Dependency using Map example
Previous Home Next

Introduction:In the case of dependency on collection using setter injection, property is the sub element of <bean ......> is used to specify the dependency of a collection i.e to be satisfied the property 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="a1" class="org.r4r.Institute">
<property name="name" value="HIMT"/>
<property name="courseDetail">
<map>
<entry key="MCA" value="75000"/>
<entry key="MBA" value="175000"/>
<entry key="BCA" value="50000"/>
<entry key="BBA" value="50000"/>
</map>
</property>
</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> courseDetail;
public void setName(String name) {
this.name = name;
}
public void setCourseDetail(Map<String, String> courseDetail) {
this.courseDetail = courseDetail;
}
public void display(){
System.out.println("Name:-\t"+name);
System.out.println("\nCourse Details:-");
Set<Map.Entry<String, String>> set=courseDetail.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"+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[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
Institute i=(Institute)f.getBean("a1");
i.display();
}
}

Output:

Name:- HIMT
Course Details:-
MCA 75000
MBA 175000
BCA 50000
BBA 50000
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: