举例一个人,他可能有多辆车,这多辆车就是一个集合。这里使用list集合。
//这是Person类
public class Person {
private String name;
private String sex;
private int age;
private double height;
private List<Car> cars;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
@Override
public String toString() {
return "Person [name=" + name + ", sex=" + sex + ", age=" + age + ", height=" + height + ", cars=" + cars + "]";
}
//这是Car类
public class Car {
private String name;
private double price;
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Car [name=" + name + ", price=" + price + "]";
}
通过配置文件进行配置
<?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.xsd">
<bean id="car" class="cn.com.xiao.Car">
<property name="name" value="大众"></property>
<property name="price" value="2000000.0"></property>
</bean>
<!-- <bean id="person" class="cn.com.xiao.Person" >
<constructor-arg value="张三" index="0"></constructor-arg>
<constructor-arg value="男" index="1"></constructor-arg>
<constructor-arg value="20" index="2"></constructor-arg>
<constructor-arg value="185" index="3"></constructor-arg>
<constructor-arg>
<bean class="cn.com.xiao.Car">
<property name="name" value="dazhong111"></property>
<property name="price" value="2000000.0"></property>
</bean>
</constructor-arg>
</bean> -->
<bean id="car1" class="cn.com.xiao.Car">
<property name="name" value="aodi"></property>
<property name="price"><value>2000000.0</value></property>
</bean>
<bean id="car2" class="cn.com.xiao.Car">
<property name="name" value="baoma"></property>
<property name="price" value="5000000"></property>
</bean>
<bean id="person" class="cn.com.xiao.Person">
<property name="name" value="zhangsn"></property>
<property name="age" value="35"></property>
<property name="height" value="186"></property>
<property name="sex" value="男"></property>
<!--配置cars集合,在property下使用list节点,在list节点下注入外部bean,或者定义内部bean-->
<property name="cars">
<list>
<ref bean="car1"/>
<ref bean="car2"/>
<bean class="cn.com.xiao.Car">
<property name="name"><value>jieda</value></property>
<property name="price" value="4000000"></property>
</bean>
</list>
</property>
</bean>
</beans>