Spring集合注入的方式

来源:互联网 发布:php处理base64 编辑:程序博客网 时间:2024/05/21 11:30

小博老师下面讲解如何为集合类型进行对象应用赋值。


下面这个beans.xml的配置能够帮助了解如何注入bean的引用对象作为集合的元素之一。甚至可以混合引用对象和简单类型,如下所示:


<?xml version="1.0" encoding="UTF-8"?>

<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-3.0.xsd">

   <bean id="javaCollection"class="com.bwf.JavaCollection">

      <property name="addressList">

        <list>

          <ref bean="address1"/>

          <ref bean="address2"/>

          <value>Pakistan</value>

       </list>

      </property>

     <property name="addressSet">

       <set>

          <ref bean="address1"/>

          <ref bean="address2"/>

          <value>Pakistan</value>

       </set>

      </property>

     <property name="addressMap">

       <map>

          <entry key="one"value="INDIA"/>

          <entry key ="two"value-ref="address1"/>

          <entry key ="three"value-ref="address2"/>

       </map>

      </property>

   </bean>

</beans>


从这个例子我们可以看出,对list,set进行引用对象赋值,使用<ref bean="address1"/>即可,其中address1是一个已经定义的bean。而对map记性引用对象赋值,需要使用<entrykey ="two"value-ref="address1"/>,value-ref指向已定义的bean。由于properties只能是字符串类型,所以不存在引用对象赋值,这里就不再演示。


0 0