不使用自動裝配前使用的是類的引用:
<?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"> <bean id="car1" class="cn.Spring.Day15autowire.Car"> <property name="carname" value="奔馳"></property> <property name="carcolor" value="紅色"></property> </bean> <bean id="stu" class="cn.Spring.Day15autowire.Student"> <property name="name" value="小明"></property> <property name="age" value="18"></property> <property name="car" ref="car1"></property> </bean> </beans>
自動裝配有五中模式:
no 默認的方式是不進行自動裝配,通過手工設置ref 屬性來進行裝配bean
byName 通過參數名 自動裝配,如果一個bean的name 和另外一個bean的 property 相同,就自動裝配。
byType 通過參數的數據類型自動自動裝配,如果一個bean的數據類型和另外一個bean的property屬性的數據類型兼容,就自動裝配
construct 構造方法中的參數通過byType的形式,自動裝配。
default 由上級標簽<beans>的default-autowire屬性確定。
使用自動裝配進行注入:
使用ByType進行裝配:
現在在來一個類使用ByType進行裝配:
報錯:因為有兩個類型,ByType無法識別到。
使用ByName進行裝配:
ByName依據的是:bean節點的id和類中定義的car名字相同則byName識別。