使用util命名空间定义集合

来源:互联网 发布:淘宝卖家版怎么登陆 编辑:程序博客网 时间:2024/05/29 13:52

问题:在property和constructor-arg标签里面定义的集合,和内部bean差不多,无法被重用和共享,外部无法引用该集合。怎样才可以定义外部的集合bean呢?

使用util命名空间

(1)导入util命名空间

<?xml version="1.0" encoding="UTF-8"?><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-4.0.xsd            http://www.springframework.org/schema/util            http://www.springframework.org/schema/util/spring-util-4.0.xsd"></beans>

(2)导入util命名空间后,会多出这些标签:
这里写图片描述
(3)配置一个List集合

    <util:list id="list1" list-class="java.util.LinkedList" value-type="java.lang.String">        <value>aaa</value>        <value>bbb</value>        <value>ccc</value>    </util:list>

list-class属性:指定了list接口的实现类型。默认是java.util.ArrayList
value-type属性:指定了集合元素的数据类型(可以不指定)
(4)配置一个Map集合

    <util:map id="map1" map-class="java.util.TreeMap" key-type="java.lang.Integer" value-type="java.lang.String">        <entry key="1" value="a"></entry>        <entry key="2" value="b"></entry>    </util:map>

map-class属性:指定了map接口的实现类型。默认是java.util.LinkedHashMap
key-type属性:指定了key的数据类型(可以不指定)
value-type属性:指定了value的数据类型(可以不指定)
(5)配置一个Properties

    <util:properties id="properties1">        <prop key="001">张三</prop>        <prop key="002">李四</prop>    </util:properties>

(6)引用外部的集合bean(和引用外部bean一样);也可以在嵌入内部(相当于内部bean了)

    <util:list id="list1">        <value>aaa</value>        <value>bbb</value>        <value>ccc</value>    </util:list>    <util:map id="map1">        <entry key="1" value="a"></entry>        <entry key="2" value="b"></entry>    </util:map>    <bean id="test1" class="com.Test">        <property name="list" ref="list1"></property>        <property name="map" ref="map1"></property>    </bean>    <bean id="test2" class="com.Test">        <property name="list">            <!-- 嵌入内部 -->            <util:list list-class="java.util.LinkedList">                <value>aaa</value>                <value>bbb</value>                <value>ccc</value>            </util:list>        </property>        <property name="map">            <!-- 嵌入内部 -->            <util:map>                <entry key="1" value="a"></entry>                <entry key="2" value="b"></entry>            </util:map>        </property>    </bean>
原创粉丝点击