自动装配
通过约定自动赋值
原则:约定优于配置
只有对象之间的依赖关系可以自动装配(自动装配只适合与ref类型,即引用类型)
default-autowire/autowire的类型:
byName:其他bean的id值=该course类的属性名
byType:其他bean的类型(class)是否与该course类的ref属性类型一致(注意:此种方式,必须满足:当前ioc容器中,只能有一个bean满足条件)
constructor:其他bean的类型(class)是否与该course类的构造方法参数的类型是否一致
全局自动装配
设置全局自动装配:在配置信息后面写: default-autowire="byName"即可,之后的bean会自动找寻是否有自动装配的属性,不用单独去写每一个bean的autowire属性,但是每个bean的简单类型照常写。
<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">
<bean id="teacher" class="com.dt.entity.Teacher" >
<property name="name" value="zs"></property>
<property name="age" value="23"></property>
</bean>
<bean id="course" class="com.dt.entity.Course">
<property name="courseName" value="java"></property>
<property name="courseHour" value="100"></property>
</bean>
</beans>
子标签装配
例如,不配置course类的teacher属性,使用自动装配找到teacher
autowire="byName"的意思:course类中,有一个引用属性,属性名为teacher,并且ioc容器中恰好配置了teacher类,且id名为teacher,就可以自动引用过来。
即bean的id值=类的属性名
<bean id="teacher" class="com.dt.entity.Teacher" >
<property name="name" value="zs"></property>
<property name="age" value="23"></property>
</bean>
<bean id="course" class="com.dt.entity.Course" autowire="byName">
<property name="courseName" value="java"></property>
<property name="courseHour" value="100"></property>
</bean>