现有员工类,它有hobby属性,是数组类型。如何用xml注入数组?
员工employee类:
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;
}
}
部门类略。
beanEmp.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">
<!--方式3,级联属性注入
-->
<bean id="dept" class="com.kiong.spring6.Dept">
<property name="deptName" value="人力部"></property>
</bean>
<bean id="emp" class="com.kiong.spring6.Employee">
<!--普通类型注入-->
<property name="name" value="David"></property>
<property name="age" value="21"></property>
<!--对象类型注入-->
<property name="dpt" ref="dept"></property>
<!--数组类型注入-->
<property name="hobby">
<array>
<value>吃饭</value>
<value>睡觉</value>
<value>打灰机</value>
</array>
</property>
</bean>
</beans>
测试类TestEmp:
package com.kiong.spring6;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestEmp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beanEmp.xml");
Employee emp = context.getBean("emp",Employee.class);
emp.work();
}
}
运行结果如下: