天天看点

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>