Spring ListFactoryBeanの例
‘
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をインスタンス化し、それを実行時に顧客のリストプロパティに注入しました。 === ソースコードをダウンロードする ダウンロードする - リンク://wp-content/uploads/2010/03/Spring-ListFactoryBean-Example.zip[Spring-ListFactoryBean-Example.zip](5KB) === リファレンス . http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/ListFactoryBean.html[ListFactoryBean Javadoc] link://tag/spring/[spring]