Spring 的 IOC 容器提供了自動裝配功能,簡化了 Bean 之間依賴關係的配置。所謂自動裝配,是指容器無需透過 <property> 或 <constructor-arg> 顯式注入屬性值或引用,即可自動完成 Bean 的依賴注入。
在 <bean> 元素中使用 autowire 屬性指定裝配模式,預設值為 no。也可在根元素 <beans> 上設定 default-autowire 屬性以改變全域預設值。
NoUniqueBeanDefinitionException 異常。id 完全一致。傳統手動注入方式:
<bean class="com.nucsoft.spring.Address" id="address"> <property name="addressName" value="beijing"/> </bean> <bean class="com.nucsoft.spring.Phone" id="phone" p:phoneNum="123456789"/> <bean id="employee" class="com.nucsoft.spring.Employee"> <property name="empName" value="emp01"/> <property name="phone" ref="phone"/> <property name="address" ref="address"/> </bean>
byName 自動裝配:
<bean id="employee" class="com.nucsoft.spring.Employee" autowire="byName"> <property name="empName" value="emp01"/> </bean>
byType 自動裝配:
<bean id="employee" class="com.nucsoft.spring.Employee" autowire="byType"> <property name="empName" value="emp01"/> </bean>
autowire 會嘗試裝配 Bean 的所有屬性,缺乏針對單一屬性的靈活控制。autowire 和 <property>,以 <property> 為準。byType 和 byName 不能同時啟用。