创建一个类Person
package com.kk.spring.beans.collections;
import java.util.List;
import com.kk.spring.beans.Car;
public class Person {
private String name;
private int age;
private List<Car> 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 + "]";
}
}
Car类创建,参照[Spring全回顾之构造方法注入值](https://blog.csdn.net/fx9590/article/details/80367518)
配置文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<!-- 配置单例的集合bean,以供多个bean 进行调用 ,需要导入util命名空间-->
<util:list id="cars">
<ref bean="car"/>
<ref bean="car2"/>
</util:list>
<!-- 通过p命名空间为bean的属性赋值,需要导入p命名空间 ,相对于传统的配置方式更加简洁-->
<bean id="person5" class="com.kk.spring.beans.collections.Person" p:age="30" p:name="Queen" p:cars-ref="cars"></bean>
</beans>
注意:需要导入p命名空间 [xmlns:p=”http://www.springframework.org/schema/p”]
写个测试类:
package com.kk.spring.beans.collections;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicaContext.xml");
public static void main(String[] args) {
Person person = (Person) ctx.getBean("person5");
System.out.println("person5:"+person);
}
结果: