The Mapfactorybean class provides developers with a way to create a specific Map collection class (HashMap and TreeMap) in the Spring bean configuration file. Here is a mapfactorybean. For example, at run time it instantiates a hashmap and injects it into a bean property.
Package Com.yiibai.common;import Java.util.map;public class Customer {private Map maps;//...}
Spring's bean configuration file.
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xsi:schemalocation=" http://www.springframework.org/schema/beanshttp:// Www.springframework.org/schema/beans/spring-beans-2.5.xsd "><bean id=" Customerbean "class=" Com.yiibai.common.Customer "><property name=" Maps "><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= "One"/><entry key= "Key2" value= "one"/><entry key= "Key3" value= "three"/></map></ Property></bean></property></bean></beans>
In addition, you can use the Util mode and <util:map> to do the same thing.
<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:util=" Http://www.springframework.org/schema/util "xsi:schemalocation="/HTTP/ www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp:// Www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-2.5.xsd "><bean Id= "Customerbean" class= "Com.yiibai.common.Customer" ><property name= "Maps" ><util:map map-class= " Java.util.HashMap "><entry key=" Key1 "value=" 1 "/><entry key=" Key2 "value=" 2 "/><entry key=" Key3 " Value= "3"/></util:map></property></bean></beans>
Please remember the envelope util mode, otherwise the following error will appear
caused by:org.xml.sax.SAXParseException:The prefix "util" for Element "Util:map" was not bound.
Execution results ...
Package Com.yiibai.common;import Org.springframework.context.applicationcontext;import Org.springframework.context.support.classpathxmlapplicationcontext;public class App {public static void main ( String[] args) { ApplicationContext context = new Classpathxmlapplicationcontext ("Springbeans.xml"); Customer cust = (customer) Context.getbean ("Customerbean"); SYSTEM.OUT.PRINTLN (Cust); }}
Output Result:
Customer [Maps={key2=two, Key1=one, key3=three}] instantiates a hashmap and injects a map attribute to the customer at run time. Download code –http://pan.baidu.com/s/1ktxsdoj http://www.yiibai.com/spring/spring-mapfactorybean-example.html
Spring Mapfactorybean Example