天天看點

Spring中集合定義

習慣了把集合定義在一個類的字段中,今天遇到想重用集合的定義,竟然不知道單獨的集合bean應該怎麼定義了,記之,以備後用。

對map來說,有一種比較搓的方法,就是直接用map的構造函數:

 1

Spring中集合定義

<bean id="symbolmap" class="java.util.hashmap">  

 2

Spring中集合定義

    <constructor-arg>  

 3

Spring中集合定義

       <map>  

 4

Spring中集合定義

         <entry>  

 5

Spring中集合定義

            <key><value><![cdata[us;djia]]></value></key>  

 6

Spring中集合定義

            <value><![cdata[us&dji]]></value>  

 7

Spring中集合定義

         </entry>  

 8

Spring中集合定義

       </map>  

 9

Spring中集合定義

    </constructor-arg>  

10

Spring中集合定義

</bean>  

11

Spring中集合定義

另一種稍微簡單的方法:

Spring中集合定義

<bean id="emails" class="org.springframework.beans.factory.config.mapfactorybean">  

Spring中集合定義

  <property name="sourcemap">  

Spring中集合定義

      <map>  

Spring中集合定義

        <entry key="pechorin" value="[email protected]"/>  

Spring中集合定義

        <entry key="raskolnikov" value="[email protected]"/>  

Spring中集合定義

        <entry key="stavrogin" value="[email protected]"/>  

Spring中集合定義

        <entry key="porfiry" value="[email protected]"/>  

Spring中集合定義

      </map>  

Spring中集合定義

  </property>  

Spring中集合定義
Spring中集合定義

對這種方法,sping還提供了listfactorybean, setfactorybean等類,這貌似是spring的一個可擴充架構,可以待以後進一步研究這個架構的實作方式。

最簡單的一種方式就是直接用spring中提供的util包:

1

Spring中集合定義

<util:map id="emails">  

2

Spring中集合定義

    <entry key="pechorin" value="[email protected]"/>  

3

Spring中集合定義

    <entry key="raskolnikov" value="[email protected]"/>  

4

Spring中集合定義

    <entry key="stavrogin" value="[email protected]"/>  

5

Spring中集合定義

    <entry key="porfiry" value="[email protected]"/>  

6

Spring中集合定義

</util:map>  

7

Spring中集合定義

使用改方法時,xml檔案頭需要使用:

Spring中集合定義

    xmlns:util="http://www.springframework.org/schema/util"

Spring中集合定義

    xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

Spring中集合定義

                        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">

引用:

<a href="http://macrochen.iteye.com/blog/392616">http://macrochen.iteye.com/blog/392616</a>

<a href="http://springindepth.com/book/in-depth-ioc-collections.html">http://springindepth.com/book/in-depth-ioc-collections.html</a>