MapFactoryBean類為開發者提供了一種在Spring的bean配置檔中創建一個具體的Map集合類(HashMap和TreeMap)。
這裏有一個MapFactoryBean。例如,在運行時它將實例化一個HashMap,並注入到一個bean屬性。
package com.xuhuhu.common; import java.util.Map; public class Customer { private Map maps; //... }
Spring 的 bean 配置檔。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="CustomerBean" class="com.xuhuhu.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="two" /> <entry key="Key3" value="three" /> </map> </property> </bean> </property> </bean> </beans>
另外,還可以使用 util 的模式和<util:map>來做到同樣的事情。
<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/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"> <bean id="CustomerBean" class="com.xuhuhu.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>
請記住包函util模式,否則會出現下麵的錯誤
Caused by: org.xml.sax.SAXParseException: The prefix "util" for element "util:map" is not bound.
執行結果...
package com.xuhuhu.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); } }
輸出結果:
Customer [maps={Key2=two, Key1=one, Key3=three}]
在運行時實例化一個HashMap和注入到客戶的映射(Map)屬性。