Spring依赖注入 — 集合属性配置

对于数组、java.util.List、java.util.Set、java.util.Map等集合对象,在注入前必须填充入一些对象至集合中,然后再将集合对象注入至所需的Bean,也可以交由Spring的IoC容器来自动维护或生成集合对象,并完成依赖注入。

 

完整实例

public class SomeBean {

    private String[] someStrArray;

    private Some[] someObjArray;

    private List<Some> someList;

    private Set<Some> someSet;

    private Map<String, Some> someMap;

    private Properties prop;

// Fieldgettersetter方法

}

 

<!-- 3Some-->

<bean id="some1" class="cn.itcast.spring.collection.Some">

<property name="val" value="some instance1" />

</bean>

<bean id="some2" class="cn.itcast.spring.collection.Some">

<property name="val" value="some instance2" />

</bean>

<bean id="some3" class="cn.itcast.spring.collection.Some">

<property name="val" value="some instance3" />

</bean>

<!-- SomeBean实例 -->

<bean id="someBean" class="cn.itcast.spring.collection.SomeBean">

<!-- String类型数组 -->

<property name="someStrArray">

<list value-type="java.lang.String">

<value>some string1</value>

<value>some string2</value>

<value>some string3</value>

</list>

</property>

<!-- 对象类型数组 -->

<property name="someObjArray">

<list value-type="cn.itcast.spring.collection.Some">

<ref bean="some1"/>

<ref bean="some2"/>

<ref bean="some3"/>

</list>

</property>

<!-- List -->

<property name="someList">

<list value-type="cn.itcast.spring.collection.Some">

<ref bean="some1"/>

<ref bean="some2"/>

<ref bean="some3"/>

</list>       

</property>

<!-- Set -->

<property name="someSet">

<set value-type="cn.itcast.spring.collection.Some">

<ref bean="some1"/>

<ref bean="some2"/>

<ref bean="some3"/>

</set>       

</property>

<!-- Map -->

<property name="someMap">

<map key-type="java.lang.String" value-type="cn.itcast.spring.collection.Some">

<entry value-ref="some1" key="key1"></entry>

<entry value-ref="some2" key="key2"></entry>

<entry value-ref="some3" key="key3"></entry>

</map>

</property>

<!-- Properties -->

<property name="prop">

<props>

<prop key="prop1_key">prop1_value</prop>

<prop key="prop2_key">prop2_value</prop>

<prop key="prop3_key">prop3_value</prop>

</props>

</property>

</bean>


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页