一、级联赋值第一种方法
1.创建Emp类
package com.bean;
public class Emp {
private String EName;
private String gender;
//员工属于某一个部门,使用对象形式表示
private Dept dept;
public void setDept(Dept dept) {
this.dept = dept;
}
public Dept getDept() {
return dept;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setEName(String EName) {
this.EName = EName;
}
public void add(){
System.out.println(EName+":"+gender+":"+dept);
}
}
2.创建Dept类
package com.bean;
public class Dept {
private String dName;
public void setdName(String dName) {
this.dName = dName;
}
@Override
public String toString() {
return "Dept{" +
"dName='" + dName + '\'' +
'}';
}
}
3.配置bean3.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 name="emp" class="com.bean.Emp">
<property name="EName" value="lucy"></property>
<property name="gender" value="male"></property>
<property name="dept" ref="dept"></property>
<property name="dept.dName" value="安保"></property>
</bean>
<bean name="dept" class="com.bean.Dept"></bean>
</beans>
4.创建测试类
public class TestBean2 {
@Test
public void testUpdate(){
//加载spring配置文件
ApplicationContext context=new ClassPathXmlApplicationContext("bean3.xml");
//获取配置创建的对象
Emp service = context.getBean("emp", Emp.class);
service.add();
}
}
二、级联赋值的第二种方法
<!-- 级联赋值,类似于外部bean配置-->
<bean id="emp" class="cn.zsp.spring5.bean.Emp">
<property name="ename" value="zsp"></property>
<property name="gender" value="男"></property>
<property name="dept" ref="dept" ></property>
</bean>
<bean id="dept" class="cn.zsp.spring5.bean.Dept">
<property name="dname" value="安保部"></property>
</bean>