August 31 2015

Spring map injection

Spring map injection

The spring core container supports injecting the primitives, array, collections and spring bean through constructor or setter dependency injection.

A map can be injected using <map> element. A <map> element represents java.util.Map. A map can contain zero or more <entry> elements. Each <entry> represents one map entry. The <entry> element takes <key> and <value> elements.

Example

In the below example, countryMap is injected using setter dependency injection by placing the <map> element inside the <property>. The map can be injected using dependency injection by placing the <map> element inside <constructor-arg>.

EmployeeDAO.java

package com.answersz.di;

import java.util.Map;

public class EmployeeDAO {

 private Map<String, String> countryMap;

 public void print() {

 for (String key : countryMap.keySet()) {
 System.out.println("Key : " + key);
 System.out.println("Value : " + countryMap.get(key));

 }
 }

 public Map<String, String> getCountryMap() {
 return countryMap;
 }

 public void setCountryMap(Map<String, String> countryMap) {
 this.countryMap = countryMap;
 }

}

mapInjection.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-3.0.xsd">

 <bean id="employeeDAO" class="com.answersz.di.EmployeeDAO">
 <property name="countryMap">
 <map>

 <entry>
 <key>
 <value>FRANCE</value>
 </key>
 <value>COUNFR</value>
 </entry>

 <entry>
 <key>
 <value>ITALY</value>
 </key>
 <value>COUNIT</value>
 </entry>

 </map>
 </property>
 </bean>

</beans>

MapInjectionTest.java

package com.answersz.di;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MapInjectionTest {

 public static void main(String[] args) {

 // Spring map injection

 ApplicationContext context = new ClassPathXmlApplicationContext(
 "mapInjection.xml");

 EmployeeDAO employeeDAO = (EmployeeDAO) context.getBean("employeeDAO");
 employeeDAO.print();

 }

}

Output

Key : FRANCE
Value : COUNFR
Key : ITALY
Value : COUNIT


Copyright © 2014. All rights reserved.

Posted August 31, 2015 by answersz in category Spring

Leave a Comment

Your email address will not be published. Required fields are marked *

*