Spring 专题
专题目录
您的位置:java > Spring专题 > Spring MapFactoryBean例子
Spring MapFactoryBean例子
作者:--    发布时间:2019-11-20
mapfactorybean类为开发者提供了一种在spring的bean配置文件中创建一个具体的map集合类(hashmap和treemap)。
这里有一个mapfactorybean。例如,在运行时它将实例化一个hashmap,并注入到一个bean属性。
package com.h3.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.h3.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.h3.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.h3.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)属性。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册