技术库 > Java

Spring依赖注入 集合属性配置

技术库:tec.5lulu.com

from:tec.5lulu.com

对于数组、java.util.List、java.util.Set、java.util.Map等集合对象,在注入前必须填充入一些对象至集合中,然后再将集合对象注入至所需的Bean,也可以交由SpringIoC容器来自动维护或生成集合对象,并完成依赖注入。  
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;
// 各Field的getter、setter方法
}
 
<!-- 3个Some-->
<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>

Spring依赖注入 集合属性配置


标签: bean spring本文链接 http://tec.5lulu.com/detail/110dtn2eh6ge285ee.html

我来评分 :6.1
0

转载注明:转自5lulu技术库

本站遵循:署名-非商业性使用-禁止演绎 3.0 共享协议

www.5lulu.com