集合类型对象 给bean注入集合
pojo类里
public class Student {
private long id;
private String name;
private int age;
private List<Address> addresses;
public Student(long id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
}
pojo类里有一个list属性
spring-ioc.xml
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd" >
<!-- 这个为无参构造的bean-->
<bean id="student" class="cn.learnbyheart.Student">
<property name="age" value="11"></property>
<property name="id" value="1"></property>
<property name="name" value="ggy"></property>
<!-- 把两个对象组成一个集合-->
<property name="addresses" >
<list>
<ref bean="address"></ref>
<ref bean="address2"></ref>
</list>
</property>
</bean>
<bean id="address" class="cn.learnbyheart.Address">
<property name="id" value="2"></property>
<property name="name" value="软件园"></property>
</bean>
<bean id="address2" class="cn.learnbyheart.Address">
<property name="id" value="2"></property>
<property name="name" value="软件园2"></property>
</bean>
</beans>
重点是property标签内,使用list标签,将两个对象组合成一个集合
测试类里
public class Test3 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-ioc.xml");
Student student = (Student) context.getBean("student");
System.out.println(student);
}
}
另外 scope作用域
- singleton 单例,表示通过Spring获取的bean是唯一的 默认
- protype 原型 表示通过spring容器获取的bean是不同的
- request 请求 表示在一次HTTP请求内有效
- session 会话 表示在一次会话内有效
requst和session只用于web