【Spring学习09】依赖配置:配置集合
Spring中通过 首先定义OrderCollect类: public class OrderCollect {
Properties Emailconfig;
List<String> Productnames;
Map<String,Object> purchaseList;
Set<Object> setOthers;
//getter and setter methods
......
@Override
public String toString() {
return "OrderCollect [Emailconfig=" + Emailconfig + ",Productnames="
+ Productnames + ",purchaseList=" + purchaseList
+ ",setOthers=" + setOthers + "]";
}
public void print(){
System.out.println(this.toString());
}
}
调用: public static void main(String[] args) throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
OrderCollect ordercollect=ctx.getBean("ordercollect",OrderCollect.class);
ordercollect.print();
//ordercollect.PaySuccess();
}
bean配置: <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.xsd">
<bean id="ordercollect" class="twm.spring.start.OrderCollect">
</bean>
</beans>
运行输出:
现在来修改配置,加点内容进去: <bean id="ordercollect" class="twm.spring.start.OrderCollect">
<!-- property对象的设置 -->
<property name="Emailconfig">
<props>
<prop key="pop">pop.twm.com</prop>
<prop key="user">support@twm.com</prop>
<prop key="pwd">123456</prop>
</props>
</property>
<!-- list对象的设置,数组的设置方式同这个一样 -->
<property name="Productnames">
<list>
<value>绿茶</value>
<value>小番茄</value>
<!-- 外部对象就用ref指向 bean id <ref bean="mybeanid" /> -->
</list>
</property>
<!-- map对象的设置 -->
<property name="purchaseList">
<map>
<entry key="SN-1137569" value="3个"/>
<entry key="SN-1137571" value="1个"/>
<!-- 外部对象就用value-ref指向 bean id <entry key ="arefkey" value-ref="mybeanid"/>-->
</map>
</property>
<!-- set对象的设置 -->
<property name="setOthers">
<set>
<value>要小票</value>
<value>放整齐包严实</value>
<!-- 外部对象就用ref指向 bean id <ref bean="mybeanid" />-->
</set>
</property>
</bean>
输出:
所有集合的value值可以是普通值类型,也可以是对象或集合: 集合合并 Spring容器也支持集合合并。合并的场景主要出现在父子集合。 <beans>
<bean id="parent" abstract="true" class="example.ComplexObject">
<property name="adminEmails">
<props>
<prop key="administrator">administrator@example.com</prop>
<prop key="support">support@example.com</prop>
</props>
</property>
</bean>
<bean id="child" parent="parent">
<property name="adminEmails">
<props merge="true">
<prop key="sales">sales@example.com</prop>
<prop key="support">support@example.co.uk</prop>
</props>
</property>
</bean>
<beans>
注意,在bean child定义中,指定property adminEmails的 这个合并行为,同样可以用在 集合合并总结: 1、list没有覆盖行为。 2、对于元素,spring合并行为维持集合原有的顺序序;父集合中的元素索引位置比子集合元素索引位置靠前。 3、不能合并不同类型的集合,比如合并Map和List。 4、merge属性必须指定给父-子继承结构中的子bean,如果指定给了父bean则不会产生预期的合并结果。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |