创建实体类
public class Dept {
private Integer deptid;
private String dname;
public Dept() {
}
public Dept(Integer deptid, String dname) {
this.deptid = deptid;
this.dname = dname;
}
public Integer getDeptid() {
return deptid;
}
public void setDeptid(Integer deptid) {
this.deptid = deptid;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
@Override
public String toString() {
return "Dept{" +
"deptid=" + deptid +
", dname='" + dname + '\'' +
'}';
}
}
public class Emp {
private Dept dept;
public Emp() {
}
public Emp(Dept dept) {
this.dept = dept;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Emp{" +
"dept=" + dept +
'}';
}
}
创建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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dept" class="com.maliqiang.bean.Dept"></bean>
<bean id="dept2" class="com.maliqiang.bean.Dept"></bean>
<!-- 通过属性注入引用类型 -->
<bean id="emp" class="com.maliqiang.bean.Emp">
<property name="dept" ref="dept2"></property>
</bean>
<!-- 通过autowire 自动装配 byName是通过id="dept" -->
<bean id="emp2" class="com.maliqiang.bean.Emp" autowire="byName"></bean>
<!-- 通过autowire 自动装配 byType是通过 类型进行匹配 如果出现两个id不同 但类型相同的bean,就分不清选择哪个,也就会报错 -->
<!-- <bean id="emp3" class="com.maliqiang.bean.Emp" autowire="byType"></bean>-->
</beans>
创建测试类
public class Test07 {
@Test
public void testGetBean1() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext7.xml");
Emp emp = applicationContext.getBean("emp", Emp.class);
System.out.println("emp = " + emp);
Emp emp2 = applicationContext.getBean("emp2", Emp.class);
System.out.println("emp2 = " + emp2);
Emp emp3 = applicationContext.getBean("emp3", Emp.class);
System.out.println("emp3 = " + emp3);
}
}