Spring 自動裝配 Bean 演練
除了使用 XML 和 Annotation 的方式裝配 Bean 以外,還有一種常用的裝配方式——自動裝配。自動裝配就是指 Spring 容器可以自動裝配(autowire)相互協作的 Bean 之間的關聯關係,將一個 Bean 注入其他 Bean 的 Property 中。
要使用自動裝配,就需要配置 <bean> 元素的 autowire 屬性。autowire 屬性有五個值,具體說明如下表所示
名稱 | 說明 |
---|---|
byName | 根據 Property 的 name 自動裝配,如果一個 Bean 的 name 和另一個 Bean 中的 Property 的 name 相同,則自動裝配這個 Bean 到 Property 中 |
byType | 根據 Property 的數據類型(Type)自動裝配,如果一個 Bean 的數據類型兼容另一個 Bean 中 Property 的數據類型,則自動裝配 |
constructor | 根據構造方法的參數的數據類型,進行 byType 模式的自動裝配 |
autodetect | 如果發現默認的構造方法,則用 constructor 模式,否則用 byType 模式 |
no | 默認情況下,不使用自動裝配,Bean 依賴必須通過 ref 元素定義 |
下面通過修改上一節中“Spring 基於 Annotation 裝配 Bean 演練”中的案例演示如何實現自動裝配。
首先將 applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--使用context命名空間,通知spring掃描指定目錄,進行註解的解析-->
<!-- context:component-scan base-package="com.mengma.annotation"/ -->
<!-- 使用 Autowire 自動裝配 Bean 配置 -->
<bean id="personDao" class="com.mengma.annotation.PersonDaoImpl" />
<bean id="personService" class="com.mengma.annotation.PersonServiceImpl" autowire="byName" />
<bean id="personAction" class="com.mengma.annotation.PersonAction" autowire="byName" />
</beans>
在上述配置文件中,用於配置 personService 和 personAction 的 <bean> 元素中除了 id 和 class 屬性以外,還增加了 autowire 屬性,並將其屬性值設置爲 byName(按屬性名稱自動裝配)。
默認情況下,配置文件中需要通過 ref 裝配 Bean,但設置了 autowire="byName",Spring 會在配置文件中自動尋找與屬性名字 personDao 相同的 <bean>,找到後,通過調用 setPersonDao(PersonDao personDao)方法將 id 爲 personDao 的 Bean 注入 id 爲 personService 的 Bean 中,這時就不需要通過 ref 裝配了。
然後,在 PersonServiceImpl 類中添加 personDao 的 setter 方法:
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
在 PersonAction 中添加 personService 的 setter 方法:
public void setPersonService(PersonService personService) {
this.personService = personService;
}
使用 JUnit 再次運行測試類中的 AnnotationTest,控制檯的顯示結果如圖:
從輸出結果中可以看出,使用自動裝配的方式同樣完成了依賴注入。
(PS: 經過實踐,Annotation 的方式裝配 Bean 的方式不必爲需要注入的屬性提供對應的 setter 方法,但是自動裝配 Bean 方式必須爲需要注入的屬性提供對應的 setter 方法!否則運行會出現異常。另外自動裝配 Bean 的方式不必再爲各個層內的調用添加Annotation(註解))