一个部门Dept有多个员工Employee。在部门类中,创建List employeeList容器来装员工对象。
在xml中创建Kiong和David员工对象,把他们注入上述List中。
Dept类:
package com.kiong.spring6;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Dept {
private List<Employee> employeeList;
private String deptName;
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
//打印员工姓名
public void printInfo(){
for (Employee employee : employeeList) {
System.out.println(employee.getName());
}
}
}
员工类:
package com.kiong.spring6;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Employee {
private String name;
private int age;
private Dept dpt;
private String[] hobby;
public Employee() {
}
public Employee(String name, int age, Dept dpt) {
this.name = name;
this.age = age;
this.dpt = dpt;
}
public String[] getHobby() {
return hobby;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public void work(){
System.out.println("员工"+name+"的年龄是"+age);
dpt.printInfo();
System.out.println("员工的爱好有:"+ Arrays.toString(hobby));
}
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 Dept getDpt() {
return dpt;
}
public void setDpt(Dept dpt) {
this.dpt = dpt;
}
}
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="emp1" class="com.kiong.spring6.Employee">
<property name="name" value="Kiong"></property>
<property name="age" value="21"></property>
</bean>
<bean id="emp2" class="com.kiong.spring6.Employee">
<property name="name" value="David"></property>
<property name="age" value="22"></property>
</bean>
<bean id="dept" class="com.kiong.spring6.Dept">
<property name="deptName" value="财务部"></property>
<property name="employeeList">
<list>
<ref bean="emp1"></ref>
<ref bean="emp2"></ref>
</list>
</property>
</bean>
</beans>
TestDept类
package com.kiong.spring6;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDept {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beanEmp.xml");
Dept dept = context.getBean("dept",Dept.class);
dept.printInfo();
}
}
输出结果: