Spring基礎篇——自動化裝配bean

  上篇博文講Spring的IOC容器時說道,雖然容器功能強大,但容器自己只是個空殼,須要咱們主動放入裝配對象,並告訴它對象之間的協做關係,而後容器才能按照咱們的指示發揮它的魔力,完成裝配bean的使命。這裏,咱們把Spring建立應用對象之間的協做關係的行爲成爲裝配。Spring提供了不少裝配bean的方式供咱們在開發中選擇,咱們經常使用到的有三種裝配機制:自動裝配、Java註解和XML配置。一般咱們將第一種稱爲隱式的裝配機制,後面兩種爲顯示的裝配機制。實際應用中,基於便利性考慮,首選的確定是隱式的自動化裝配機制,只有當須要注入的bean的源碼不是由本身的程序來維護,而是引入第三方的應用組件的時候,才考慮顯示的方式裝配bean。固然,各類裝配方式在實際應用中是能夠自由選擇搭配的,編碼過程當中也沒必要拘泥哪種,適用就好。本篇博文先來說述隱式的裝配機制——bean的自動化裝配。
spring

   你必定很好奇Spring是怎麼來實現其自動化裝配機制的,其實Spring主要經過下面兩個方面來實現:編程

  • 組件掃描——經過開啓組件掃描功能讓Spring能夠自動發現應用上下文中的bean;
  • 自動裝配——自動知足組件之間的依賴關係。

  下面,咱們分別來看看Spring如何經過組件掃描自動裝配來爲咱們的應用程序自動化的裝配bean。咱們先定義一個汽車接口:數組

1 package spring.facade;
2 
3 public interface Car {
4     void drive();
5 }

  組件掃描

  組件掃描的要義在於經過掃描控制,讓Spring自動的去發現應用程序中的bean。不過程序中的對象那麼多,Spring怎麼知道哪些對象是須要它去管理建立的呢?這就涉及到Spring的一個組件註解——@Component,被該註解標註的類即爲Spring的組件類,Spring容器加載過程當中會自動的爲該類建立bean(PS:實際上Spring的組件註解按照語義化的分類還有@Controller @Repository @Service等等,分別做用於控制層、持久層和業務層,此處僅是舉例演示,不作區分講解)。因此,咱們能夠將接口的一個實現標註上該註解,代表實現類是要被Spring建立實例的——
安全

 1 package spring.impl;
 2 
 3 import org.springframework.stereotype.Component;
 4 import spring.facade.Car;
 5 
 6 @Component
 7 public class QQCar implements Car {
 8     @Override
 9     public void drive() {
10         System.out.println("開QQ車");
11     }
12 }

  不過,Spring的註解掃描默認是不開啓的,因此咱們還須要顯示的配置註解啓動。這裏一樣有兩種方式,Java註解和XML的方式,咱們分別展現出來——app

  Java配置類CarConfig ide

package spring.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
public class CarConfig {
}

   XML配置文件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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!--啓動註解掃描-->
    <context:component-scan base-package="spring"/>
</beans>

  接下來咱們編寫測試類,看看Spring是否是自動的去發現了咱們註解爲組件的bean併爲咱們建立了對象——測試

 1 package spring.test;
 2 
 3 import org.junit.Test;
 4 import org.junit.runner.RunWith;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.test.context.ContextConfiguration;
 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 8 import spring.config.CarConfig;
 9 import spring.impl.QQCar;
10 import static org.junit.Assert.assertNotNull;
11 
12 /**
13  * 註解釋義:
14  * @RunWith(SpringJUnit4ClassRunner.class)  測試在Spring環境中運行
15  * @ContextConfiguration  上下文配置註解,指定配置文件(Java類或XML文件)的位置
16  */
17 @RunWith(SpringJUnit4ClassRunner.class)
18 //@ContextConfiguration(classes = CarConfig.class) //加載Java配置類的方式
19 @ContextConfiguration(locations = "classpath:resource/applicationContext.xml") //加載XML配置的方式
20 public class CarTest {
21     @Autowired
22     private QQCar car ;
23 
24     @Test
25     public void carTest(){
26         assertNotNull(car);
27     }
28 }

  雖然如今的編程趨勢是愈來愈多的使用Java註解的方式,可是上面的測試你會發現,經過XML註解的方式可以測試成功,而Java註解的方式倒是失敗的,測試會拋出NoSuchBeanDefinitionException的異常,表示沒有QQCar的組件定義,也就是Spring沒有發現它,Why? 緣由也很簡單,那就是基於Java註解的方式啓動的註解掃描默認狀況下只能掃描配置類所在的包以及其的子包,若是要明確掃描其它包中的組件,須要在啓動掃描的註解 @ComponetScan 中顯示的註明,如改爲 @ComponentScan("spring.impl"),上訴的測試就能經過了。若是有多個包要掃描,能夠這樣配置:@ComponentScan(basePackages = {"spring.impl","spring.test"})  不過這樣字符串的表示方式是類型不安全的,並且寫死包名的方式不利於代碼重構,咱們能夠指定包中所含的類或接口來指定要掃描的包,因而能夠這樣標註: @ComponentScan(basePackageClasses = QQCar.class) ,多個包一樣能夠用{}來以數組形式的表示。不過這樣對重構依然不友好,最好的方式就是在要掃描的包中定義一個空標接口,該接口僅僅用來指定包掃描的範圍,如此將重構的影響降到最低。this

 

  自動裝配

  前文的講述只是闡明如何將一個類定義成Spring的組件並啓動Spring的組件掃描,並且咱們已經經過測試證明,Spring確實掃描到了咱們指定的組件類併爲咱們建立了對象。不過,建立的對象只是獨立的存在,並無和其餘對象產生依賴協做;實際應用中,對象之間的依賴協做是再常見不過了,而要將Spring經過組件掃描爲咱們建立的對象根據實際業務創建起相互的依賴協做,就須要利用Spring的自動裝配。便於演示,咱們再定義一個Man類,Man的工做就是開車,咱們先經過構造器注入的方式來知足依賴,看Spring是否會給咱們自動注入咱們須要的Car的實例對象——編碼

 

package spring.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import spring.facade.Car;

@Component
public class Man {
    
    private Car car;

    public Man() {
    }

    @Autowired
    public Man(QQCar car) {
        this.car = car;
    }

    public void work() {
        car.drive();
    }
}

 

  測試方法——

 

 1 package spring.test;
 2 
 3 import org.junit.Test;
 4 import org.junit.runner.RunWith;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.test.context.ContextConfiguration;
 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 8 import spring.config.CarConfig;
 9 import spring.impl.Man;
10 
11 @RunWith(SpringJUnit4ClassRunner.class)
12 @ContextConfiguration(classes = CarConfig.class)
13 public class CarTest {
14 
15     @Autowired
16     Man man;
17 
18     @Test
19     public void carTest() {
20         man.work();
21     }
22 }

 

  如以上代碼,測試固然是成功的,在測試類中,Man做爲組件類被Spring掃描並建立了一個對象實例,該實例調用work方法的時候,須要Car的實例對象,而咱們在有參構造函數上經過 @Autowired 註解代表了對象的依賴關係,程序運行過程當中,Spring會自動爲咱們注入Car的實例對象來知足對象依賴,這就是自動裝配的精要所在。實際上,不僅是構造器上能夠用 @Autowired 註解,在屬性的Setter方法上,甚至普通的方法上,均可以用@Autowired 註解來知足對象之間的依賴,實現自動注入的功能——

 1 package spring.impl;
 2 
 3 
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.stereotype.Component;
 6 import spring.facade.Car;
 7 
 8 @Component
 9 public class Man {
10     private Car car;
11 
12     public Man() {
13     }
14     //構造器實現自動裝配
15     //    @Autowired
16     public Man(QQCar car) {
17         this.car = car;
18     }
19 
20     //Setter方法實現自動裝配
21     // @Autowired
22     public void setCar(QQCar car) {
23         this.car = car;
24     }
25     //普通方法實現自動裝配
26     @Autowired
27     public void insertCar(QQCar car) {
28         this.car = car;
29     }
30 
31     public void work() {
32         car.drive();
33     }
34 }

  咱們將Man類中添加不一樣的方法測試,依然是能夠成功的。不過有一點要注意,在非構造器實現自動裝配的時候,雖然咱們沒有本身new對象,但Spring建立實例會經過Man的默認的構造器,此時的Man類中若是定義了有參構造器,就必定要把默認構造器構造出來,否則會拋無默認構造器的異常,記住:必定養成類中寫默認構造器的習慣,便於擴展。

 

  自動裝配的歧義性

   若是你足夠細心,你會發現博主上面知足自動裝配的測試代碼中,注入的Car並無採用多態的寫法,代碼顯得很低級。其實我是爲了測試經過,故意注入了具體的實現,實際業務中固然不會這麼侷限的去寫代碼。由於博主Car的接口還有一個奔馳車的實現類BenzCar,若是用多態的寫法,自動裝配會有產生歧義性問題,會拋 NoUniqueBeanDefinitionException 異常。那麼,面對這種歧義性,如何去解決呢?你必定知道Spring容器管理的每一個bean都會有一個ID做爲惟一標識,在上面的示例中,咱們描述QQCar類爲Spring的組件的時候並無明確的設置ID,可是Spring默認會將組件類的類名首字母小寫來做爲bean的ID,而咱們也可根據咱們本身的業務須要自定義ID標識——

 

package spring.impl; import org.springframework.stereotype.Component; import spring.facade.Car; //這裏指定 chenbenbuyi 爲組件的ID @Component("chenbenbuyi") public class QQCar implements Car { @Override public void drive() { System.out.println("開QQ車"); } }

 

  但是測試發現,這並無解決接口參數在自動裝配時的歧義性問題,由於在組件上自定義ID是一種後發行爲,當你讓Spring在裝配階段從多個接口實現中選擇要自動注入的對象實例時,Spring沒法選擇——就比如你只跟我說你要開一輛車,每輛車也都有惟一的車牌號,但我仍是不知道你要開什麼車。怎麼辦呢?這裏有多種解決方案,咱們能夠經過 @Primary註解將咱們明確須要自動注入的實現類標註爲首選的bean,就想這樣——

 

 1 package spring.impl;
 2 
 3 import org.springframework.context.annotation.Primary;
 4 import org.springframework.stereotype.Component;
 5 import spring.facade.Car;
 6 
 7 @Component
 8 @Primary
 9 public class BenzCar implements Car {
10     @Override
11     public void drive() {
12         System.out.println("開奔馳車");
13     }
14 }

 

  當自動裝配的時候,Spring面對歧義性時,會優先選擇被標註爲首選的bean進行自動注入。固然,咱們還能夠採用限定符註解,在使用@Autowired 完成自動裝配的時候限定只讓某個bean做爲自動注入的bean——

 1 package spring.impl;
 2 
 3 
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.beans.factory.annotation.Qualifier;
 6 import org.springframework.stereotype.Component;
 7 import spring.facade.Car;
 8 
 9 @Component
10 public class Man {
11     private Car car;
12 
13     public Man() {
14     }
15     //普通方法實現自動裝配
16     @Autowired
17     @Qualifier("chenbenbuyi") //限定ID爲 chenbenbuyi 的bean被裝配進來
18     public void insertCar(Car car) {
19         this.car = car;
20     }
21 
22     public void work() {
23         car.drive();
24     }
25 }

   此,關於Spring的自動裝配就闡述得差很少了,下一節系列文章會接着講解Spring的另外兩種經常使用的裝配機制——Java註解和XML配置。博文所述皆爲原創,如要轉載,請註明出處;若是闡述得不恰當的地方,歡迎指教,不勝感激。

相關文章
相關標籤/搜索