Spring boot創建自定義starter的完整步驟

目錄

前言:

看看官方的starter

自定義自己的starter

測試:

總結


這篇文章主要給大家介紹了關於Spring boot創建自定義starter的相關資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Spring boot具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧

前言:

Springboot的出現極大的簡化了開發人員的配置,而這之中的一大利器便是springboot的starter,starter是springboot的核心組成部分,springboot官方同時也爲開發人員封裝了各種各樣方便好用的starter模塊,例如:

  • spring-boot-starter-web//spring MVC相關
  • spring-boot-starter-aop //切面編程相關
  • spring-boot-starter-cache //緩存相關

starter的出現極大的幫助開發者們從繁瑣的框架配置中解放出來,從而更專注於業務代碼,而springboot能做的不僅僅停留於此,當面對一些特殊的情況時,我們可以使用我們自定義的springboot starter。
在創建我們自定義的starter之前呢,我們先看看官方是怎麼說的:

  • 模塊

在springboot官方文檔中,特別提到,我們需要創建兩個module ,其中一個是autoconfigure module  一個是 starter module ,其中 starter module 依賴 autoconfigure module

但是,網上仍然有很多blog在說這塊的時候其實會發現他們其實只用了一個module,這當然並沒有錯,這點官方也有說明:

You may combine the auto-configuration code and the dependency management in a single module if you do not need to separate those two concerns

//如果不需要將自動配置代碼和依賴項管理分離開來,則可以將它們組合到一個模塊中。

  • 命名規範

springboot 官方建議springboot官方推出的starter 以spring-boot-starter-xxx的格式來命名,第三方開發者自定義的starter則以xxxx-spring-boot-starter的規則來命名,事實上,很多開發者在自定義starter的時候往往會忽略這個東西(因爲不看官方文檔很難知道這件事情。同時也不會造成其他的後果,主要是顯得不夠專業)。

看看官方的starter

瞭解了這兩點之後,那麼下面讓我們一塊去探索spingboot starter的奧祕吧。

按照springboot官方給的思路,starter的核心module應該是autoconfigure,所以我們直接去看spring-boot-autoconfigure裏面的內容。

當Spring Boot啓動時,它會在類路徑中查找名爲spring.factories的文件。該文件位於META-INF目錄中。打開spring.factories文件,文件內容太多了,爲了避免我水篇幅,我們只看其中的一部分:

1

2

3

4

5

6

7

# Auto Configure

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\

org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\

org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\

org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\

org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\

我們可以發現一些比較眼熟的單詞,比如Aop,Rabbit,Cache ,當springboot啓動的時候,將會嘗試加載這些配置類,如果該路徑下存在該類的話,則將運行它,並初始化與該配置類相關的bean。

點開一個看看:

1

2

3

4

5

6

7

8

@Configuration

@ConditionalOnClass({RabbitTemplate.class, Channel.class})

@EnableConfigurationProperties({RabbitProperties.class})

@Import({RabbitAnnotationDrivenConfiguration.class})

public class RabbitAutoConfiguration {

   

  //...代碼略..

}

我們先來了解一下這幾個註解:

@ConditionalOnClass :條件註解,當classpath下發現該類的情況下進行自動配置。

@EnableConfigurationProperties:外部化配置

@Import :引入其他的配置類

當然,這並不是一種通用的套路,查看其他的配置類,我們會發現其標註的註解往往也是有所區別的。

自定義自己的starter

首先我們新建一個maven項目,引入以下依賴:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<dependencies>

    <dependency>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-autoconfigure</artifactId>

    </dependency>

  </dependencies>

  <dependencyManagement>

    <!-- 我們是基於Springboot的應用 -->

    <dependencies>

      <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-dependencies</artifactId>

        <version>2.1.0.RELEASE</version>

        <type>pom</type>

        <scope>import</scope>

      </dependency>

    </dependencies>

  </dependencyManagement>

然後我們創建一個person類,用作後期我們測試的bean

1

2

3

4

5

6

7

8

9

10

public class Person {

 

  //屬性

  private int age;

  private String name;

  private String gender;

   

  /*此處省略getter and setter and toStering*/

 

}

然後我們也創建一個PersonConfigProperties來完成我們屬性的注入

1

2

3

4

5

6

7

8

9

10

11

12

13

14

@ConfigurationProperties(prefix = "mystarter.config.student")

public class PersonConfigProperties {

 

 

  private String name;

  private int age;

  private String gender;

 

  /*

  其他的配置信息。。。。

   */

   

  /*此處省略getter and setter and toStering*/

}

最後創建我們的自動配置類MyStarterAutoConfiguration.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

@Configuration

@EnableConfigurationProperties(PersonConfigProperties.class)

@ConditionalOnClass(Person.class)

public class MyStarterAutoConfiguration {

 

 

  @Bean

  @ConditionalOnProperty(prefix = "mystarter.config", name = "enable", havingValue = "true")

  public Person defaultStudent(PersonConfigProperties personConfigProperties) {

    Person person = new Person();

    person.setAge(personConfigProperties.getAge());

    person.setName(personConfigProperties.getName());

    person.setGender(personConfigProperties.getGender());

    return person;

  }

}

  • @ConditionalOnClass:當類路徑classpath下有指定的類的情況下進行自動配置
  • @ConditionalOnMissingBean:當容器(Spring Context)中沒有指定Bean的情況下進行自動配置
  • @ConditionalOnProperty(prefix = “example.service”, value = “enabled”, matchIfMissing = true),當配置文件中example.service.enabled=true時進行自動配置,如果沒有設置此值就默認使用matchIfMissing對應的值
  • @ConditionalOnMissingBean,當Spring Context中不存在該Bean時。
  • @ConditionalOnBean:當容器(Spring Context)中有指定的Bean的條件下
  • @ConditionalOnMissingClass:當類路徑下沒有指定的類的條件下
  • @ConditionalOnExpression:基於SpEL表達式作爲判斷條件
  • @ConditionalOnJava:基於JVM版本作爲判斷條件
  • @ConditionalOnJndi:在JNDI存在的條件下查找指定的位置
  • @ConditionalOnNotWebApplication:當前項目不是Web項目的條件下
  • @ConditionalOnWebApplication:當前項目是Web項目的條件下
  • @ConditionalOnResource:類路徑下是否有指定的資源
  • @ConditionalOnSingleCandidate:當指定的Bean在容器中只有一個,或者在有多個Bean的情況下,用來指定首選的Bean

我感覺這是不是做好了?

我不要你覺得,我要我覺得

最後我們最重要的一步:

在resourecs文件目錄下創建META-INF,並創建我們自己的spring.factories,並把我們的 MyStarterAutoConfiguration添加進去

1

2

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\

com.jdkcb.mystarter.config.MyStarterAutoConfiguration

最後打包成jar包,在我們新的項目裏面測試:

測試:

引入我們的starter,當然也可以在本地直接引入我們的my-spring-boot-starter項目

1

2

3

4

5

6

7

<dependency>

    <groupId>com.jdkcb</groupId>

    <artifactId>my-spring-boot-starter</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <scope>system</scope>

    <systemPath>${project.basedir}/src/main/resources/lib/my-spring-boot-starter-0.0.1-SNAPSHOT.jar</systemPath>

  </dependency>

在application.properties配置文件中添加我們相應的配置

1

2

3

4

mystarter.config.enable=true

mystarter.config.person.name=小明

mystarter.config.person.age=5

mystarter.config.person.gender=男

新建一個測試的Controller:

1

2

3

4

5

6

7

8

9

10

11

12

@RestController

public class TestController {

 

  @Autowired

  private Person person;

 

  @RequestMapping("/getPerson")

  private Person getStudent() {

    return person;

  }

 

}

啓動項目,在瀏覽器地址欄輸入 http://127.0.0.1:8080/getPerson ,結果如下

1

{"age":5,"name":"小明","gender":"男"}

大功告成~

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。

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