一:List
1.在spring中可以通过一组内置的XML标签(列如List,Set)
2.配置java.util.List类型的属性,需要知道List标签,在标签里包含一些元素,这些标签可以通过<value>指定简单的常亮值,通过
<ref>指定对其他Bean的引用,通过<bean>指定内置的Bean的定义,通过<null>指定空元素,甚至内嵌集合。
3.数组的定义和List一样都使用<List>标签
4.配置java.util.Set需要使用Set标签,定义元素的方法和List一样。
二:例子
1.创建一个Person类
package com.collection.dhx;
import java.util.List;
import com.dhx.Car;
public class Person {
private String name;
private int age;
private List<Car> cars;
public Person() {
super();
}
public Person(String name, int age, List<Car> cars) {
super();
this.name = name;
this.age = age;
this.cars = cars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", cars=" + cars + "]";
}
}
2.创建一个Car类
package com.dhx;
public class Car {
private String brand;
private String corp;
private double price;
private int maxSpeed;
public Car(String brand, String corp, int maxSpeed) {
super();
this.brand = brand;
this.corp = corp;
this.maxSpeed = maxSpeed;
}
public Car(String brand, String corp, double price) {
super();
this.brand = brand;
this.corp = corp;
this.price = price;
}
public Car() {
super();
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getCorp() {
return corp;
}
public void setCorp(String corp) {
this.corp = corp;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price + ", maxSpeed=" + maxSpeed + "]";
}
}
3.在applicationContext.xml中配置
<!-- 集合属性 -->
<bean id="person3" class="com.collection.dhx.Person">
<property name="name" value="wangzi"></property>
<property name="age" value="24"></property>
<property name="cars">
<list>
<ref bean="car"/>
<null></null>
<bean id="car" class="com.dhx.Car">
<property name="brand" value="heilong"></property>
<property name="corp" value="yunnan"></property>
<property name="maxSpeed" value="1234"></property>
</bean>
</list>
</property>
</bean>
4.在Mian类中打印
//创建spring容器对象,applicationContext是IOC容器,实际上也是一个接口
//ClassPathXmlApplicationContext:是ApplicationContext的接口实现类,是在类的路径下实现该类
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Person p=(Person) ctx.getBean("person3");
System.out.println(p);
5.List和Set用法相同,这里就不介绍了