Spring 专题
专题目录
您的位置:java > Spring专题 > Spring SetFactoryBean实例
Spring SetFactoryBean实例
作者:--    发布时间:2019-11-20
setfactorybean 类为开发者提供了一种可在 spring bean 配置文件创建一个具体的set集合(hashset 和 treeset)。
这里有一个 listfactorybean。例如,在运行时它将实例化 hashset,并注入到一个 bean 属性中。
package com.h3.common;

import java.util.set;

public class customer 
{
	private set sets;
	//...
}
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="sets">
			<bean class="org.springframework.beans.factory.config.setfactorybean">
				<property name="targetsetclass">
					<value>java.util.hashset</value>
				</property>
				<property name="sourceset">
					<list>
						<value>one</value>
						<value>2</value>
						<value>three</value>
					</list>
				</property>
			</bean>
		</property>
	</bean>

</beans>
另外,还可以使用 util的模式 和<util:set> 来做到同样的事情。
<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="sets">
			<util:set set-class="java.util.hashset">
				<value>one</value>
				<value>2</value>
				<value>three</value>
			</util:set>
		</property>
	</bean>

</beans>
请记住必须包函 util 模式,否则会出现下面的错误:
caused by: org.xml.sax.saxparseexception: 
	the prefix "util" for element "util:set" 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("applicationcontext.xml");

    	customer cust = (customer)context.getbean("customerbean");
    	system.out.println(cust);
    	
    }
}

输出结果:

customer [sets=[2, one, three]] type=[class java.util.hashset]
实例化 hashset,在运行时注入到客户的set集合属性。



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