Spring 的自动装配 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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
- default-autowire="byname"> <!-- 通过byName全局自动装配 -- >
|
1、通过autowrite="byName": Student的Teacher 属性必须等于 teacher<bean>的Id
- 1. <bean
id="teacher"
class="cn.tri.vo.Teacher" p:name="yefan" p:age="18"></bean>
- 2. <bean
id="stu"
class="cn.tri.vo.Student" p:id="6" p:name="liming" p:age="8"
autowire="byName">
|
2、通过autowrite="byType": byType类型 会自动寻找一个与Teacher类的bean,但是类型相同的多个bean通过ByType注入会报错
3、通过autowrite="Constrcuctor": constrcutor根据构造方法寻找,其他bean的类型是否与该类的构造器参数方法一致
Spring 的自动装配 通过注解的方式:
@Component("stu") 总注解
dao层注解:@Respository
service层注解:@Service
controller层注解:@Controller
使用注解有个前提,必须在application.xml文件中配置
<context:component-scan package="配置有上面注解的包名">
- @Component("TeacherDaoImpl") //id="TeacherDaoImpl" 的bean
- public class TeacherDaoImpl implements TeacherDao{
- public void getshow() {
- System.out.println("我是一名中国老师");
- }
- }
|
等同于
<bean id="TeacherDaoImpl" class="cn.tri.dao.impl"></bean>