如何在SpringBoot中建立自己的啟動器?
也許你有一個內部庫包或一個在整個應用程式環境中常用的開源庫,如果要在多個Spring Boot應用程式中使用它,為它建立一個Spring Boot啟動器可能會很有用。
總觀
Spring Boot啟動器包含兩個模組:
- 自動配置 ,這是執行繁重工作和設定模組
- 啟動 啟動程式模組,它將您的lib庫包、@autoconfiguration和所有依賴項包裝在一個依賴項中
讓我們看一下名為@autoconfiguration的機制。這聽起來比實際更復雜。
在啟動時,Spring Boot會掃描類路徑,查詢 位於META-INF 目錄中名為spring.factories的 所有檔案,並對其進行處理。這些檔案包含單個鍵org.springframework.boot.autoconfigure.EnableAutoConfiguration = ,其值設定為常規@Configurtion 類的列表。
它會檢查每個@Configurtion 是否應該包含它並最終使用它。所謂使用就是加入Spring上下文,這樣能被別人發現,通過@autowired自動注入這些類。
當Spring Boot考慮使用它時,將新增條件; 就像@ConditionalOnClass 一樣,它添加了一個條件,只有當類路徑中存在指定的@Configurtion 類時才會將這個類包含進來。
實現自動配置
Spring Boot建議為模組命名模式:-spring-boot-autoconfigure , 還要宣告我們應該為所有屬性新增字首,以免弄亂任何名稱空間。讓我們尊重它。
比如這裡我們的模組將命名為request-logging-spring-boot-autoconfigure, 幷包含兩個類 - @ Confiration類和一個屬性類,用於公開可在application.properties中 配置的一些屬性。
讓我們從pom開始吧。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot</artifactId> <version>${spring-boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> <version>${spring-boot.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <version>${spring-boot.version}</version> <optional>true</optional> </dependency>
前兩個依賴項是使用Spring Boot和自動配置類,spring-boot-configuration-processor 是一個從@ConfigurationProperties 建立元資料檔案的工具
下面是配置屬性類
@ConfigurationProperties(prefix = "com.requestlogging") public class RequestLoggingProperties { ..... }
下面一步定義RequestLoggingAutoConfiguration :我們使用@EnableConfigurationProperties 啟用屬性 並新增兩個條件:
- @ConditionalOnWebApplication 表示只有Spring Boot應用程式是Web應用程式時才包含我們的配置。
- @ConditionalOnClass 定義RequestContextLoggingFilter 必須存在於類路徑才能包含配置它。
@Configuration @ConditionalOnWebApplication @ConditionalOnClass(RequestContextLoggingFilter.class) @EnableConfigurationProperties(RequestLoggingProperties.class) public class RequestLoggingAutoConfiguration { @Autowired private RequestLoggingProperties requestLoggingProperties; @Bean @Order(1) @ConditionalOnMissingBean public RequestContextLoggingFilter requestContextLoggingFilter() { return new RequestContextLoggingFilter(requestLoggingProperties.getRequestHeaderId(), requestLoggingProperties.getLogIdentifier()); } }
如果Spring Boot包含了我們這個配置,那麼如果@ConditionalOnMissingBean 有效,它將初始化我們的過濾器bean:new一個RequestContextLoggingFilter例項 。只有當我們的Spring上下文中沒有bean存在,我們的bean才會被初始化。
使用autoconfigure模組, Spring建議為啟動器命名模式:-spring-boot-starter . 這裡我們命名為request-logging-spring-boot-starter :
<dependency> <groupId>com.jdon</groupId> <artifactId>request-logging-spring-boot-autoconfigure</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
啟動器需要包含使此啟動器工作的所有活動依賴項,否則無法工作。
這樣別人就可以使用上面配置使用你的庫包了。