“ ListFactoryBean ”类为开发人员提供了一种在Spring的Bean配置文件中创建具体的List集合类(ArrayList和LinkedList)的方法。
这是一个ListFactoryBean示例,它将在运行时实例化ArrayList并将其注入bean属性。
package com.mkyong.common;
import java.util.List;
public class Customer
{
private List lists;
//...
}
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.mkyong.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>1</value>
<value>2</value>
<value>3</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.mkyong.common.Customer">
<property name="lists">
<util:list list-class="java.util.ArrayList">
<value>1</value>
<value>2</value>
<value>3</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.mkyong.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 [lists=[1, 2, 3]] Type=[class java.util.ArrayList]
您已实例化ArrayList,并在运行时将其注入到Customer的lists属性中。
下载源代码
下载它– Spring-ListFactoryBean-Example.zip (5KB)
参考
标签: 春天
翻译自: https://mkyong.com/spring/spring-listfactorybean-example/