1. 程式人生 > 實用技巧 >Spring 自動掃描與裝配

Spring 自動掃描與裝配

通常你可以在 xml 配置檔案中,宣告一個 bean 或者 component,然後 Spring 容器會檢查和註冊你的 bean 或 component。

實際上,Spring 支援自動掃描 bean 或 component,你可以不必再在 xml 檔案中繁瑣的宣告 bean,Spring 會自動掃描並檢查你指定包的 bean 或 component。以下列舉一個簡單的 Spring Project,包含了 Controller、Service、DAO 層,由此分析下手動配置和自動掃描的不同。

首先建立一個新的 maven 工程 SpringAuto,開啟 Terminal,選擇 File->Open New Terminal,在終端中輸入:

mvn archetype:generate -DgroupId=com.shiyanlou.spring -DartifactId=SpringAuto -DarchetypeArtifactId=maven-archetype-quickstart

選擇 File->Open Workspace 切換工作空間,選擇 SpringAuto 目錄,必須切換到該目錄下,否則識別不了專案。

修改 pom.xml 檔案,新增 Spring 的依賴:

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.shiyanlou.spring</groupId>
    <artifactId>SpringAuto</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>SpringAuto</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>5.1.1.RELEASE</spring.version>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
    </dependencies>
</project>

手動配置 component

先看一下正常手動配置一個 bean。

DAO 層,建立包 com.shiyanlou.spring.dao,建立 CustomerDAO.java。

內容如下:

package com.shiyanlou.spring.dao;

public class CustomerDAO {
    @Override
    public String toString(){
        return "Hello , This is CustomerDAO";
    }
}

Service 層,建立包 com.shiyanlou.spring.services,建立 CustomerService.java 內容如下:

package com.shiyanlou.spring.services;

import com.shiyanlou.spring.dao.CustomerDAO;

public class CustomerService {
    CustomerDAO customerDAO;

    public void setCustomerDAO(CustomerDAO customerDAO) {
        this.customerDAO = customerDAO;
    }

    @Override
    public String toString() {
        return "CustomerService [customerDAO = " + customerDAO + "]";
    }
}

在目錄 src/main/resources 建立並配置 SpringCustomer.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"
    xsi:schemaLocation = "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id = "customerService" class = "com.shiyanlou.spring.services.CustomerService">
        <property name = "customerDAO" ref = "customerDAO" />
    </bean>

    <bean id = "customerDAO" class = "com.shiyanlou.spring.dao.CustomerDAO" />

</beans>

最後,建立 App.java 檔案,在包路徑 com.shiyanlou.spring.common 下。內容如下:

package com.shiyanlou.spring.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.shiyanlou.spring.services.CustomerService;

public class App {
    public static void main( String[] args ) {
        ApplicationContext context =
        new ClassPathXmlApplicationContext(new String[] {"SpringCustomer.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");
        System.out.println(cust);

    }
}

執行

mvn compile
mvn exec:java -Dexec.mainClass="com.shiyanlou.spring.common.App"

實驗結果如下:

自動掃描元件

用註釋 @Component 來表示這個 Class 是一個自動掃描元件。CustomerDAO.java 的內容如下:

package com.shiyanlou.spring.dao;

import org.springframework.stereotype.Component;

@Component
public class CustomerDAO
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }
}

CustomerService.java 的內容如下:

package com.shiyanlou.spring.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shiyanlou.spring.dao.CustomerDAO;

@Component
public class CustomerService
{
    @Autowired
    CustomerDAO customerDAO;

    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }
}

配置檔案 SpringCustomer.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/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <context:component-scan base-package = "com.shiyanlou.spring"/>

</beans>

注意:以上 xml 檔案中,加入了 context:component-scan 標籤,beans 中也加入了標籤,這樣就將 Spring 的自動掃描特性引入,base-package 表示元件的存放位置,Spring 將掃描對應資料夾下的 bean(用 @Component 註釋過的),將這些 bean 註冊到容器中。

最後執行結果與手動配置的結果一致。

自定義掃描元件名稱

上例中,預設情況下,Spring 將把元件 Class 的第一個字母變成小寫,來作為自動掃描元件的名稱,例如將 CustomerService 轉變為 customerService,你可以用 customerService 這個名字呼叫元件,如下:

CustomerService cust = (CustomerService)context.getBean("customerService");

也可以像下面這樣,建立自定義的元件名稱:

@Service("AAA")
public class CustomerService
...

但是得新增下面的程式碼:

import org.springframework.stereotype.Service;

可以呼叫自己定義的元件了,如下:

CustomerService cust = (CustomerService)context.getBean("AAA");

自動掃描元件的註釋型別

有 4 種註釋型別,分別是:

1、@Component —— 表示一個自動掃描 component。
2、@Repository —— 表示持久化層的 DAO component。
3、@Service —— 表示業務邏輯層的 Service component。
4、@Controller —— 表示表示層的 Controller component。

在專案中,我們可以將所有自動掃描元件都用 @Component 註釋,Spring 將會掃描所有用 @Component 註釋過得元件。實際上,@Repository 、@Service 、@Controller 三種註釋是為了加強程式碼的閱讀性而創造的,可以在不同的應用層中,用不同的註釋,我們可以在上一個專案的基礎上改一下注釋,如下:
DAO 層:

package com.shiyanlou.spring.dao;

import org.springframework.stereotype.Repository;

@Repository
public class CustomerDAO
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }
}

Service 層:

package com.shiyanlou.spring.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shiyanlou.spring.dao.CustomerDAO;

@Service
public class CustomerService
{
    @Autowired
    CustomerDAO customerDAO;

    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }
}

自動掃描中過濾元件

1). Filter Component - include

下例演示了用 “filter” 自動掃描註冊元件,這些元件只要匹配定義的 “regex” 的命名規則,Class 前就不需要用 @Component 進行註釋。

DAO 層,CustomerDAO.java 如下:

package com.shiyanlou.spring.dao;

public class CustomerDAO
{
    @Override
    public String toString() {
        return "Hello , This is CustomerDAO";
    }
}

Service 層,CustomerService.java 如下:

package com.shiyanlou.spring.services;

import org.springframework.beans.factory.annotation.Autowired;
import com.shiyanlou.spring.dao.CustomerDAO;

public class CustomerService
{
    @Autowired
    CustomerDAO customerDAO;

    @Override
    public String toString() {
        return "CustomerService [customerDAO=" + customerDAO + "]";
    }

}

SpringFiltering.xml 配置如下:

 <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/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <context:component-scan base-package = "com.shiyanlou.spring" >

        <context:include-filter type = "regex"
                       expression = "com.shiyanlou.spring.dao.*DAO.*" />

        <context:include-filter type = "regex"
                       expression = "com.shiyanlou.spring.services.*Service.*" />

    </context:component-scan>

</beans>

以上 xml 檔案中,所有檔名字,只要包含 DAO 和 Service( DAO._,_Service. )關鍵字的,都將被檢查註冊到 Spring 容器中。

建立 App.java 並執行如下:

package com.shiyanlou.spring.common;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lei.customer.services.CustomerService;

public class App
{
    public static void main( String[] args )
    {
        ApplicationContext context =
        new ClassPathXmlApplicationContext(new String[] {"SpringFiltering.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");
        System.out.println(cust);

    }
}

執行結果與之前相同。

2). Filter Component——exclude
也可以用 exclude,制定元件避免被 Spring 發現並被註冊到容器中。以下配置排除用 @Service 註釋過的元件:

<context:component-scan base-package = "com.shiyanlou.spring" >
        <context:exclude-filter type = "annotation"
            expression = "org.springframework.stereotype.Service" />
</context:component-scan>

以下配置排除包含 DAO 關鍵字的元件:

<context:component-scan base-package = "com.shiyanlou.spring" >
        <context:exclude-filter type = "regex"
            expression = "com.shiyanlou.spring.dao.*DAO.*" />
</context:component-scan>

excludeFilters 是指明哪些類不被掃描到
相應地
includeFilters 是指明只掃描哪些類