对象的自动装配 DI
装配的方式—-对对象中的那个属性对象赋值
1.构造方法
ApplicationContext.xml(autowire=”constructor”)
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean name="controller" class="controller.StudentController" autowire="constructor"></bean>
<bean name="service" class="service.StudentService" autowire="constructor"></bean>
<bean name="dao" class="dao.StudentDao"></bean>
</beans>
2.set方法
ApplicationContext.xml(autowire=”byName”)
<!-- 某一个bean中的属性名 对应 另一个bean的name或者id名-->
<bean name="dao" class="dao.StudentDao"></bean>
<bean name="service" class="service.StudentService" autowire="byName"></bean>
<bean name="controller" class="controller.StudentController" autowire="byName"></bean>
ApplicationContext.xml(autowire=”byType”)
<!-- bean对象中的属性类型与另一个bean对象的class类型一致-->
<bean name="dao" class="dao.StudentDao"></bean>
<bean name="service" class="service.StudentService" autowire="byType"></bean>
<bean name="controller" class="controller.StudentController" autowire="byType"></bean>
如果对象中的属性是抽象类(可能多个子类)、接口类型
(可能多个子类实现接口)——-属性是没有办法直接创建对象赋值
a.利用是构造方法方式自动装配
先按照类型匹配 刚好就一个(子类) 直接赋值
如果类型发现(匹配的子类)不止一个对应 再按照属性名与bean的name或id匹配 成功匹配 就赋值
b.利用无参数构造方法+set方法进行自动装配
byName形式 按照名字进行找寻 找不到就没有 找到就装配
byType形式 如果有两个以上对应的类型 标签配置时直接报错(采用内部形式/ref自己指定的形式
)