当传参为集合(包括 数组、List、 Set、 Map 、Properties)时,如何配置xml
Person.java
public class Person
{
private String name;
private String[] nick;
private List<String> color;
private Set like;
private Map<String,Integer> score;
private Properties prop;
//省略setter和getter、toString方法
}
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="com.lyx.service.Person">
<!-- private String name;-->
<property name="name">
<value>小小<value>
</property>
<!-- <property name="name" value="小小"> -->
<!-- private String[] nick;-->
<property name="nick">
<list>
<value>贝贝</value>
<value>哼哼</value>
<value>大头</value>
</list>
</property>
<!-- private List<String> color;-->
<property name="color">
<list>
<value>红色</value>
<value>绿色</value>
<value>蓝色</value>
</list>
</property>
<!-- private Set like; set集合没有显示指定泛型,所以在里面加啥都行-->
<property name="like">
<set>
<value>足球</value>
<value>吉他</value>
<list>
<ref bean="gd"/>
<ref bean="pd"/>
</list>
<props>
<prop key="音乐">《好久不见》</prop>
<prop key="电影">《假如爱有来生》</prop>
</props>
</set>
</property>
<!-- private Map<String,Integer> score;-->
<property name="score">
<map>
<entry key="语文" value="55"/>
<entry key="数学" value="65"/>
<entry key="英语" value="17"/>
</map>
</property>
<!-- private Properties prop;-->
<property name="prop">
<props>
<prop key="身高">175cm</prop>
<prop key="年龄">22</prop>
<prop key="体重">68kg</prop>
</props>
</property>
</bean>
<!--这两只狗都有name属性,第一只用setter方法传参,第二只用构造器传参-->
<bean id="gd" class="com.lyx.service.GunDog" p:name="二哈"/>
<bean id="pd" class="com.lyx.service.PetDog" c:_0="旺财"/>
</beans>
所以集合中可以指定如下子元素
- value: 指定集合元素是基本类型或者String类型
- ref:指定集合集合元素是Spring容器中另一个Bean
- bean:指定集合集合元素是一个Bean
- list、set、map、props:嵌套集合