推荐视频:尚硅谷-Spring5框架最新版教程(idea版)
这是我觉得很不错的一套视频,我的spring系列的文章全是学习上述视频的学习笔记
基于xml自动装配
自动装配有两种类型:基于名称、基于类型
1 基于名称
autowride="byName"
是根据类中的属性名来进行装配的,也就是说,属性名和参照的id值要保持一致
1.1 基类
public class Employer {
private Department dept;
public void setDept(Department dept) {
this.dept = dept;
}
@Override
public String toString() {
return "Employer{" +
"dept=" + dept +
'}';
}
}
public class Department {
@Override
public String toString() {
return super.toString();
}
}
1.2 配置文件
<?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="employer" class="com.xtc.entity.Employer" autowire="byName" />
<bean id="dept" class="com.xtc.entity.Department"/>
</beans>
1.3 测试类
public class EmployerTest {
@Test
public void test01(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
Employer employer = context.getBean("employer", Employer.class);
System.out.printf(employer.toString());
}
}
2 基于类型
autowride="byType"
原理:根据类中属性的类型,在配置文件中找类型匹配的进行自动装配。但是,当有两个类型相同的bean时。会装配失败
2.1 配置文件
基类、测试类的代码可以沿用基于名称的
<?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="employer" class="com.xtc.entity.Employer" autowire="byType" />
<bean id="dept" class="com.xtc.entity.Department"/>
</beans>