Spirngboot-自定義Starter

一.Spring Boot Starter簡介

Starter是Spring Boot中的一個非常重要的概念,Starter相當於模塊,它能將模塊所需的依賴整合起來並對模塊內的Bean根據環境( 條件)進行自動配置。使用者只需要依賴相應功能的Starter,無需做過多的配置和依賴,Spring Boot就能自動掃描並加載相應的模塊。

例如在Maven的依賴中加入spring-boot-starter-web就能使項目支持Spring MVC,並且Spring Boot還爲我們做了很多默認配置,無需再依賴spring-web、spring-webmvc等相關包及做相關配置就能夠立即使用起來。

二.Starter的開發步驟

編寫Starter非常簡單,與編寫一個普通的Spring Boot應用沒有太大區別,總結如下:

1.新建Maven項目,在項目的POM文件中定義使用的依賴;
2.新建配置類,寫好配置項和默認的配置值,指明配置項前綴;
3.新建自動裝配類,使用@Configuration和@Bean來進行自動裝配;
4.新建spring.factories文件,指定Starter的自動裝配類;

三.Starter的開發示例

下面,我就以創建一個自動配置來講一下各個步驟及細節。
1.新建Maven項目,在項目的POM文件中定義使用的依賴。

 <dependencies>
     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-configuration-processor</artifactId>
         <optional>true</optional>
     </dependency>

     <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-autoconfigure</artifactId>
     </dependency>
 </dependencies>   

2.新建配置類,寫好配置項和默認的配置值,指明配置項前綴。

@ConfigurationProperties("example.service")
public class StarterServiceProperties {

    private String config;

    private boolean enabled;

    public void setConfig(String config) {
        this.config = config;
    }

    public String getConfig() {
        return config;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }
}

指定配置項前綴爲example.service,各配置項均有默認值,默認值可以通過模塊使用者的配置文件進行覆蓋。

3.新建自動裝配類,使用@Configuration@Bean來進行自動裝配。

@Configuration
@EnableConfigurationProperties(StarterServiceProperties.class)
public class StarterAutoConfigure {

    /***
     * 注意:構建SpringBoot項目時候會自動增加plugin 工具,starter 不需要boot啓動類
     * 如果install 時報錯和工具相關,需要刪除plugin相關配置
     */

    @Autowired
    private StarterServiceProperties properties;

    @Bean
    @ConditionalOnMissingBean(StarterService.class)
    @ConditionalOnProperty(prefix = "example.service", value = "enabled", havingValue = "true")
    StarterService starterService (){
        StarterService starterService = new StarterService();
        starterService.setConfig(properties.getConfig());
        return starterService;
    }
}

4.新建spring.factories文件,指定Starter的自動裝配類。

# 配置自動注入的類
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.bootstarter.StarterAutoConfigure

spring.factories文件位於resources/META-INF目錄下,需要手動創建;
org.springframework.boot.autoconfigure.EnableAutoConfiguration後面的類名說明了自動裝配類,如果有多個 ,則用逗號分開;
使用者應用(SpringBoot)在啓動的時候,會通過org.springframework.core.io.support.SpringFactoriesLoader讀取classpath下每個Starter的spring.factories文件,加載自動裝配類進行Bean的自動裝配;

至此,整個Starter開發完畢,Deploy到中央倉庫或Install到本地倉庫後即可使用

四.Starter的使用

1.創建Maven項目,依賴剛纔發佈的es-starter包。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <!-- 依賴自定義starter -->
    <dependency>
        <groupId>com</groupId>
        <artifactId>boot-starter</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

只需依賴剛纔開發的es-starter即可

2.根據要求進行配置

# starter 配置文件
example.service.config  = abc-des-dde,SSS-DRS-RE,SDR-SDFR-XXX
example.service.enabled = false

3.編寫應用程序啓動類。

// 根據example.service.enabled 參數配置是否進行自動裝配
@Component
@ConditionalOnExpression("${example.service.enabled:true}")
public class ServiceTest implements ApplicationRunner {

    @Autowired
    private StarterService starterService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(Arrays.toString(starterService.split(",")));
    }
}

5.運行程序測試

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

2019-08-29 14:28:27.061  INFO 9844 --- [           main] com.demo.BootDemoApplication             : Starting BootDemoApplication on Kerwin with PID 9844 (C:\Users\Administrator\Desktop\Codes\KerwinBoots\boot-demo\target\classes started by Administrator in C:\Users\Administrator\Desktop\Codes\KerwinBoots)
2019-08-29 14:28:27.064  INFO 9844 --- [           main] com.demo.BootDemoApplication             : No active profile set, falling back to default profiles: default
2019-08-29 14:28:28.317  INFO 9844 --- [           main] com.demo.BootDemoApplication             : Started BootDemoApplication in 1.733 seconds (JVM running for 2.975)
[abc-des-dde, SSS-DRS-RE,SDR-SDFR-XXX]

運行程序,觀察控制檯輸出: 源碼可見: https://github.com/kkzhilu/KerwinBoots | boot_starter 分支

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章