Spring Map Factory, Spring Map Configuration


 

Spring Map Factory, Spring Map Configuration

In this tutorial you will learn about Spring Map Factory and also see how to use map in spring framework.

In this tutorial you will learn about Spring Map Factory and also see how to use map in spring framework.

Spring Map Factory

Ths MapFactoryBean is a simple factory for shared Map instance. The map element is defined in the xml bean definitions. The setSourceMap method set the source Map which is written in xml map element. The SetTargetListClass method set the class to use target Map.

Week.java

package list.factory.example;

import java.util.Map;

public class Week {
	private Map days;

	public Map getDays() {
		return days;
	}

	public void setDays(Map days) {
		this.days = days;
	}

	@Override
	public String toString() {
		return "Days [lists=" + days + "]";

	}
}

AppMain.java

package list.factory.example;

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

public class AppMain {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		Week weekday = (Week) context.getBean("week");
		System.out.println(weekday);
	}
}

context.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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<!-- Map Factory  -->

  <bean id="week2" class="map.factory.example.Week">
    <property name="days2">
      <bean class="org.springframework.beans.factory.config.MapFactoryBean">
        <property name="targetMapClass">
          <value>java.util.HashMap</value>
        </property>
        <property name="sourceMap">
          <map>
        <entry key="Key1" value="Sunday" />
        <entry key="Key2" value="Monday" />
        <entry key="Key3" value="Tuesday" />
        <entry key="Key4" value="Wednesday" />
        <entry key="Key5" value="Thursday" />
        <entry key="Key6" value="Friday" />
        <entry key="Key7" value="Saturday" />
      </map>
        </property>
      </bean>
    </property>
  </bean>
  
<!-- End -->


</beans>

When you run this application it will display message as shown below:


Days [lists={Key2=Monday, Key1=Sunday, Key4=Wednesday, Key3=Tuesday, Key6=Friday, Key5=Thursday, Key7=Saturday}]

Download this example code

Ads