Spring ListFactoryBean實例

ListFactoryBean”類為開發者提供了一種在Spring的bean配置檔中創建一個具體的列表集合類(ArrayList和LinkedList)。
這裏有一個 ListFactoryBean 示例,在運行時它將實例化一個ArrayList,並注入到一個 bean 屬性。
package com.xuhuhu.common;

import java.util.List;

public class Customer
{
	private List lists;
	//...
}
Spring bean配置檔 - applicationContext.html 檔的內容。
<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="lists">
			<bean class="org.springframework.beans.factory.config.ListFactoryBean">
				<property name="targetListClass">
					<value>java.util.ArrayList</value>
				</property>
				<property name="sourceList">
					<list>
						<value>one</value>
						<value>2</value>
						<value>three</value>
					</list>
				</property>
			</bean>
		</property>
	</bean>

</beans>
另外,還可以使用 util 模式和<util:list> 來達到同樣的目的。
<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="lists">
			<util:list list-class="java.util.ArrayList">
				<value>one</value>
				<value>2</value>
				<value>three</value>
			</util:list>
		</property>
	</bean>

</beans>
請記住要包函 util 模式,否則會出現下麵的錯誤
Caused by: org.xml.sax.SAXParseException:
	The prefix "util" for element "util:list" 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(
				"applicationContext.xml");

		Customer cust = (Customer) context.getBean("CustomerBean");
		System.out.println(cust);

	}
}

輸出結果

Customer [lists=[one, 2, three]] Type=[class java.util.ArrayList]
在運行時實例化ArrayList並注入列表到客戶的屬性。

上一篇: Spring集合 (List,Set,Map,Properties) 實例 下一篇: Spring SetFactoryBean實例