如何理解Spring中的@Autowired?

@Autowired 簡介

@Autowired 註解用於描述類中的屬性,構造方法,set方法,配置方法等,用於告訴Spring框架按照指定規則爲屬性注入值(DI)。spring

@Autowired 應用入門

基於以下API設計,進行代碼實現進而分析@Autowired應用分析。
imageapi

第一步:設計Cache接口框架

package com.cy.pj.common.cache;
public interface Cache {
 
}

第二步: 設計Cache接口實現類WeakCache,並交給spring管理。函數

package com.cy.pj.common.cache;
 
import org.springframework.stereotype.Component;
 
@Component
    
public class WeakCache implements Cache{
 
}

第二步: 設計Cache接口實現類SoftCache,並交給spring管理。單元測試

package com.cy.pj.common.cache;
 
@Component
public class SoftCache implements Cache{
…
}

第三步:設計單元測試類測試

package com.cy.pj.common.cache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
    
public class CacheTests {
    @Autowired
    @Qualifier("softCache")
    private Cache cache;
    
    @Test
    public void testCache() {
        System.out.println(cache);
    }
}

基於單元測試,分析@Autowired應用(底層經過反射技術爲屬性賦值)。this

說明:Spring框架在項目運行時假如發現由他管理的Bean對象中有使用@Autowired註解描述的屬性,能夠按照指定規則爲屬性賦值(DI)。其基本規則是:首先要檢測容器中是否有與屬性類型相匹配的對象,假若有而且只有一個則直接注入。其次,假如檢測到有多個,還會按照@Autowired描述的屬性名查找是否有名字匹配的對象,有則直接注入,沒有則拋出異常。最後,假如咱們有明確要求,必需要注入類型爲指定類型,名字爲指定名字的對象還能夠使用@Qualifier註解對其屬性或參數進行描述(此註解必須配合@Autowired註解使用)。

@Autowired 應用進階

@Autowired 註解在Spring管理的Bean中也能夠描述其構造方法,set方法,配置方法等,其規則依舊是先匹配方法參數類型再匹配參數名,基於以下圖的設計進行分析和實現:spa

image

第一步:定義SearchService類並交給Spring管理設計

package com.cy.pj.common.service;
@Component
public class SearchService{

  private Cache cache;
  @Autowired
  public SearchService(@Qualifier("softCache")Cache cache){
     this.cache=cache;
  }
  public Cache getCache(){
     return this.cache;
  }
}
@Qualifier能夠描述構造方法參數,但不能夠描述構造方法。

第二步:定義SearchServiceTests單元測試類。code

package com.cy.pj.common.service;
@Component
public class SearchServiceTests{

  private SearchService searchService;
  @Test
  void testGetCache(){
     System.out.println(searchService.getCache())
  }
}
能夠嘗試在SearchService中添加無參構造函數和setCache(Cache cache)方法,而後使用@Autowired描述setCache方法,並基於@Qualifier註解描述setCache方法參數。分析進行注入過程。

總結(Summary)

本小節講述了,在Spring框架中使用@Autowired註解描述類中屬性、構造方法時的注入規則。而後深刻理解其注入過程。

相關文章
相關標籤/搜索