Spring模式註解裝配
定義:一種用於宣告在應用中扮演“元件”角色的註解。
舉例:@Component、@Service、@Configuration
裝配:<context:component-scan>(Spring 2.5) @ComponentScan(Spring 3.0)
複製程式碼
Component的派生性:
定義一級註解類,用的是annotation方式:
複製程式碼

@Target @Retention @Document都是java自帶的註解:
複製程式碼




@Repository是spring的註解,標註為倉儲。

新建一個類,注入前面寫好的一級元件。

完成引導類,注入bean。
Component的層次性:


再次執行,結果不變。
Spring @Enable模組裝配
定義:具備相同領域的功能元件集合,組合所形成一個獨立的單元
舉例:@EnableWebMvc @EnableAutoConfiguration等
實現:註解方式、程式設計方式
註解驅動方式:
複製程式碼

configuration,裡面配置了Bean:

獲取bean:

介面程式設計方式:

這裡匯入的是上面Seletor:

在seletor中就可以加一些分支、判斷和其他的方法。
接下來的步驟跟註解方式一樣。
HelloWorldImportSelector -> HelloWorldConfiguration -> HelloWorld
相比較下,註解方式方便,但是程式設計方式比註解方式更為靈活。
Spring 條件裝配
定義:Bean裝配的前置判斷
舉例:@Profile、@Conditional
實現:註解方式、程式設計方式
複製程式碼
@Profile:配置化條件裝配 @Conditional: 程式設計條件裝配
@Profile('java 8') Lambda 求和:

新建一個service介面
看到紅框部分我都蒙了,以為是lambda表示式,查一下才知道這個叫做“變長變數”,是jdk1.5的新特性。可以傳入多個值,型別就是前面制定的Integer。
實現這個介面,進行求和

用lambda進行求和。

紅框部分設定Profile,他就會去掃描service包下,帶有java8註解的Service進行裝配。

按照視訊中的敲會出現這個錯誤:這是因為新增了資料庫元件,所以autoconfig會去讀取資料來源配置,而新建的專案還沒有配置資料來源,所以會導致異常出現。
解決方法:去掉資料庫依賴。

@Condition 程式設計方式進行裝配:

新建一個類,紅色的metadata是從ConditionOnSystemProperty裡面拿他的屬性。
獲取傳進來的user.name 還有值,進行比較。

@Conditional :通過@Conditional註解可以根據程式碼中設定的條件裝載不同的bean,在設定條件註解之前,先要把裝載的bean類去實現Condition介面,然後對該實現介面的類設定是否裝載的條件

這裡傳進去user.name還有value,是我本機的名字。
然後到 ConditionalOnSystemProperty註解類,註解類再通過@Condition跳到OnSystemPropertyCondition,裡面進行判斷,傳進來的value和本機的user.name進行比較,相等返回true。

這個bean就能被獲取到,執行 成功。

Springboot 自動裝配
定義:基於約定大於配置的原則,實現Spring元件自動裝配的目的。
裝配:模式註解、@Enable模組、條件裝配、工廠載入機制
實現:啟用自動裝配、實現自動裝配、配置自動裝配實現。
複製程式碼