1. 程式人生 > 其它 >spring——Spring自動裝配(基於註解)

spring——Spring自動裝配(基於註解)

從 Java 5 開始,Java 增加了對註解(Annotation)的支援,它是程式碼中的一種特殊標記,可以在編譯、類載入和執行時被讀取,執行相應的處理。

開發人員可以通過註解在不改變原有程式碼和邏輯的情況下,在原始碼中嵌入補充資訊。

Spring 從 2.5 版本開始提供了對註解技術的全面支援,我們可以使用註解來實現自動裝配,簡化 Spring 的 XML 配置。

Spring 通過註解實現自動裝配的步驟如下:

  1. 引入依賴
  2. 開啟元件掃描
  3. 使用註解定義 Bean
  4. 依賴注入

1. 引入依賴

使用註解的第一步,就是要在專案中引入以下 Jar 包。

  • org.springframework.core-5.3.13.jar
  • org.springframework.beans-5.3.13.jar
  • spring-context-5.3.13.jar
  • spring-expression-5.3.13.jar
  • commons.logging-1.2.jar
  • spring-aop-5.3.13.jar

注意,除了 spring 的四個基礎 jar 包和 commons-logging-xxx.jar 外,想要使用註解實現 Spring 自動裝配,還需要引入Spring 提供的 spring-aop 的 Jar 包。

2. 開啟元件掃描

Spring 預設不使用註解裝配 Bean,因此我們需要在 Spring 的 XML 配置中,通過 <context:component-scan> 元素開啟 Spring Beans的自動掃描功能。開啟此功能後,Spring 會自動從掃描指定的包(base-package 屬性設定)及其子包下的所有類,如果類上使用了 @Component 註解,就將該類裝配到容器中。

3. 使用註解定義 Bean

Spring 提供了以下多個註解,這些註解可以直接標註在 Java 類上,將它們定義成 Spring Bean。

註解 說明
@Component 該註解用於描述 Spring 中的 Bean,它是一個泛化的概念,僅僅表示容器中的一個元件(Bean),並且可以作用在應用的任何層次,例如 Service 層、Dao 層等。

使用時只需將該註解標註在相應類上即可。
@Repository 該註解用於將資料訪問層(Dao 層)的類標識為 Spring 中的 Bean,其功能與 @Component 相同。
@Service 該註解通常作用在業務層(Service 層),用於將業務層的類標識為 Spring 中的 Bean,其功能與 @Component 相同。
@Controller 該註解通常作用在控制層(如 Struts2 的 Action、SpringMVC 的 Controller),用於將控制層的類標識為 Spring 中的 Bean,其功能與 @Component 相同。

4. 基於註解方式實現依賴注入

我們可以通過以下註解將定義好 Bean 裝配到其它的 Bean 中。

註解 說明
@Autowired 可以應用到 Bean 的屬性變數、setter 方法、非 setter 方法及建構函式等,預設按照 Bean 的型別進行裝配。

@Autowired 註解預設按照 Bean 的型別進行裝配,預設情況下它要求依賴物件必須存在,如果允許 null 值,可以設定它的 required 屬性為 false。如果我們想使用按照名稱(byName)來裝配,可以結合 @Qualifier 註解一起使用
@Resource 作用與 Autowired 相同,區別在於 @Autowired 預設按照 Bean 型別裝配,而 @Resource 預設按照 Bean 的名稱進行裝配。

@Resource 中有兩個重要屬性:name 和 type。
  • Spring 將 name 屬性解析為 Bean 的例項名稱,type 屬性解析為 Bean 的例項型別。
  • 如果指定 name 屬性,則按例項名稱進行裝配;
  • 如果指定 type 屬性,則按 Bean 型別進行裝配;
  • 如果都不指定,則先按 Bean 例項名稱裝配,如果不能匹配,則再按照 Bean 型別進行裝配;如果都無法匹配,則丟擲 NoSuchBeanDefinitionException 異常。
@Qualifier 與 @Autowired 註解配合使用,會將預設的按 Bean 型別裝配修改為按 Bean 的例項名稱裝配,Bean 的例項名稱由 @Qualifier 註解的引數指定。

示例

1. 建立一個名為 my-spring-autowire-demo 的 Java 工程。

2. 將以下 jar 包匯入到專案中。

  • org.springframework.core-5.3.13.jar
  • org.springframework.beans-5.3.13.jar
  • spring-context-5.3.13.jar
  • spring-expression-5.3.13.jar
  • commons.logging-1.2.jar
  • spring-aop-5.3.13.jar


bean.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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd">
   
    <!--開啟元件掃描功能-->
    <context:component-scan base-package="net.biancheng.c"></context:component-scan>
</beans>