SetFactoryBean

‘クラスは、SpringのBean構成ファイルで具体的なSetコレクション(HashSetおよびTreeSet)を作成する方法を開発者に提供します。

ListFactoryBeanの例を次に示します。実行時にHashSetをインスタンス化し、Beanプロパティに注入します

package com.mkyong.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.mkyong.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>1</value>
                        <value>2</value>
                        <value>3</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.mkyong.common.Customer">
        <property name="sets">
            <util:set set-class="java.util.HashSet">
                <value>1</value>
                <value>2</value>
                <value>3</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.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);

    }
}

Ouput

Customer[sets=[3, 2, 1]]Type=[class java.util.HashSet]....

実行時にHashSetをインスタンス化し、それをCustomerのsetsプロパティに注入しました。

=== ソースコードをダウンロードする

ダウンロードする - リンク://wp-content/uploads/2010/03/Spring-SetFactoryBean-Example.zip[Spring-SetFactoryBean-Example.zip](5KB)

=== リファレンス

.  http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/SetFactoryBean.html[SetFactoryBean

Javadoc]

link://tag/spring/[spring]