前言:在网上找了许多资料,没有找到如何在spring容器注入list的对象属性,在此记录一下。
实体类:Student
package com.sy.springdemo.pojo;
public class Student {
private String name;
private String sex;
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;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + "]";
}
}
实体类:Teacher
package com.sy.springdemo.pojo;
import java.util.List;
public class Teacher {
private String name;
private String job;
private List<Student> listStu;
public List<Student> getListStu() {
return listStu;
}
public void setListStu(List<Student> listStu) {
this.listStu = listStu;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "Teacher [name=" + name + ", job=" + job + ", listStu="
+ listStu + "]";
}
}
applicationContext.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 学生 -->
<bean id="student" class="com.sy.springdemo.pojo.Student">
<property name="name" value="zhangsan"></property>
<property name="sex" value="nan"></property>
</bean>
<!-- 老师 -->
<bean id="teacher" class="com.sy.springdemo.pojo.Teacher">
<property name="name" value="张老师"></property>
<property name="job" value="语文老师"></property>
<!-- 单个 -->
<property name="listStu" ref="student"></property>
</bean>
</beans>
方式二:
<?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="student" class="com.sy.springdemo.pojo.Student">
<property name="name" value="zhangsan"></property>
<property name="sex" value="nan"></property>
</bean>
<!-- 老师 -->
<bean id="teacher" class="com.sy.springdemo.pojo.Teacher">
<property name="name" value="张老师"></property>
<property name="job" value="语文老师"></property>
<!-- 多个 -->
<property name="listStu">
<list>
<bean class="com.sy.springdemo.pojo.Student">
<property name="name" value="眼镜"></property>
<property name="sex" value="女"></property>
</bean>
<bean class="com.sy.springdemo.pojo.Student">
<property name="name" value="丽丽"></property>
<property name="sex" value="男"></property>
</bean>
</list>
</property>
</bean>
</beans>
如果还有更好的办法欢迎讨论,欢迎批评,欢迎讨论。