matsukaz's blog

Agile, node.js, ruby, AWS, cocos2d-xなどなどいろいろやってます

p-namespaceの利用方法

Spring 2.0より"p-namespace"という特殊な名前空間が用意されました。"p-namespace"は、XMLによる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 name="hoge" class="com.example.Hoge">
        <property name="email" value="fuga@example.com"/>
    </bean>
</beans>

だったのに対し、"p-namespace"を利用すると

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean name="hoge" class="com.example.Hoge" p:email="fuga@example.com"/>
</beans>

と記述することができます。
同じクラスから複数のオブジェクトを生成する場合などは、abstractの定義を行うことで毎回クラス名を指定をしなくて済みます。マスタの定義をXMLで行う場合などで便利かもです。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean name="hoge" class="com.example.Hoge" abstract="true"/>
    <bean name="foo" class="com.example.Foo">
        <constructor-arg>
            <list>
                <bean parent="hoge" p:email="fuga1@example.com"/>
                <bean parent="hoge" p:email="fuga2@example.com"/>
                <bean parent="hoge" p:email="fuga3@example.com"/>
            </list>
        </constructor-arg>
    </bean>
</beans>