使用setter注入
实体类:
public class Emp {
private Integer eid;
private String ename;
private Integer age;
private Dept dept;
public Dept getDept() {
return dept;
}
@Override
public String toString() {
return "Emp{" +
"eid=" + eid +
", ename='" + ename + '\'' +
", age=" + age +
", dept=" + dept +
'}';
}
public void setEid(Integer eid) {
this.eid = eid;
}
public void setEname(String ename) {
this.ename = ename;
}
public void setAge(Integer age) {
this.age = age;
}
public void setDept(Dept dept) {
this.dept = dept;
}
}
public class Dept {
private Integer did;
private String dname;
public void setDid(Integer did) {
this.did = did;
}
public void setDname(String dname) {
this.dname = dname;
}
@Override
public String toString() {
return "Dept{" +
"did=" + did +
", dname='" + dname + '\'' +
'}';
}
}
spring配置文件
<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="emp" class="com.feng.pojo.Emp">
<property name="eid" value="1"></property>
<property name="ename" value="峰"></property>
<property name="age" value="22"></property>
<!-- 级联赋值 -->
<property name="dept" ref="dept"></property>
<property name="dept.dname" value="财务部"></property>
<!-- 级联赋值2 -->
<!--<property name="dept" ref="dept"></property>-->
</bean>
<bean id="dept" class="com.feng.pojo.Dept">
<!-- 方法2 -->
<!--<property name="did" value="1"></property>
<property name="dname" value="技术部"></property>-->
</bean>
</beans>
使用构造注入
- 在emp 中可以删除其他属性的getset方法,踩坑点:级联属性赋值一定要get方法
- 在emp中添加构造方法
<bean id="dept" class="com.feng.pojo.Dept">
</bean>
<bean id="emp" class="com.feng.pojo.Emp">
<constructor-arg value="1"></constructor-arg>
<constructor-arg value="峰"></constructor-arg>
<constructor-arg value="22"></constructor-arg>
<constructor-arg ref="dept"></constructor-arg>
<property name="dept.dname" value="财务部"></property>
</bean>