當(dāng)前位置:首頁(yè) > 公眾號(hào)精選 > 架構(gòu)師社區(qū)
[導(dǎo)讀]引言 什么是Spring Boot Starter呢?我們直接來看看官網(wǎng)是怎么介紹的吧。 ? Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that


引言

什么是Spring Boot Starter呢?我們直接來看看官網(wǎng)是怎么介紹的吧。

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technologies that you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project.

納尼,一大堆的英文,這還有興趣接著往下看嗎?是不是看到這直接退出了。都到門口了,不進(jìn)來喝杯茶再走嘛?看都看到這了還是接著繼續(xù)往下看吧。我們先不解釋這一段話是什么意思,我們可以看看starter的出現(xiàn)給我們解決了什么問題。我們還是以上述官網(wǎng)的例子來進(jìn)行說明比如說我們需要在Spring 中適應(yīng)JPA來操作數(shù)據(jù)庫(kù)。在沒有springBoot-starter之前,我們需要引入jpa的步驟

  • 通過 maven 引入jdbc的依賴、以及jpa相關(guān)的各種依賴
  • 編寫 jpa相關(guān)的配置文件
  • 網(wǎng)上各種查詢找資料進(jìn)行調(diào)試,調(diào)試的過程對(duì)于新手可能會(huì)有點(diǎn)奔潰會(huì)遇到各種奇奇怪怪的問題, jar包沖突啊,這個(gè) jar包下載不下來,缺少某個(gè) jar包。
  • 終于在經(jīng)歷千辛萬苦,哼次哼次的解決各種問題之后終于把項(xiàng)目跑起來了,然后把這次整合 jpa遇到的問題,以及整合的步驟都一一的詳細(xì)記錄下來。方便下次在需要整合 jpa的時(shí)候直接 copy就好了。我們以前在沒有 starter之前是不是都是這么玩的。這樣的缺點(diǎn)是不是也非常顯著,比如過程復(fù)雜、需要不停的粘貼復(fù)制(不過這是程序員經(jīng)常干的事情了,也不在乎多一兩次了)、整合其它組件到自己的項(xiàng)目變的困難,效率低下。這也就造成了 996的程序員比較多了(晚上就不能夠回去 69了)。 保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter

SpringBoot Starter的出現(xiàn)

我們可以看下SpringBoot 現(xiàn)在都為我們提供有哪些starter,我這邊這截圖了部分starter,更多的請(qǐng)點(diǎn)擊https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-starters保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starterstarter的實(shí)現(xiàn):雖然我們每個(gè)組件的starter實(shí)現(xiàn)各有差異,但是它們基本上都會(huì)使用到兩個(gè)相同的內(nèi)容:ConfigurationPropertiesAutoConfiguration。因?yàn)?code style="font-size: 14px;margin-right: 2px;margin-left: 2px;font-family: "Operator Mono", Consolas, Monaco, Menlo, monospace;word-break: break-all;color: rgb(53, 148, 247);background: rgba(59, 170, 250, 0.1);display: inline-block;padding-right: 2px;padding-left: 2px;border-radius: 2px;height: 21px;line-height: 22px;">Spring Boot提倡“「約定大于配置」”這一理念,所以我們使用ConfigurationProperties來保存我們的配置,并且這些配置都可以有一個(gè)默認(rèn)值,即在我們沒有主動(dòng)覆寫原始配置的情況下,默認(rèn)值就會(huì)生效。除此之外,starterConfigurationProperties還使得所有的配置屬性被聚集到一個(gè)文件中(一般在resources目錄下的application.properties),這樣我們就告別了Spring項(xiàng)目中XML地獄。starter的出現(xiàn)幫把我們把各種復(fù)雜的配置都封裝起來了,讓我們真正的可以達(dá)到了開箱即用。不僅降低了我們使用它的門檻,并且還大大提高了我們的開發(fā)效率。正如前面所說《SpringBoot自動(dòng)裝配》讓我們有更多的時(shí)間去陪女朋友。

實(shí)現(xiàn)自己的SpringBoot Starter

命名規(guī)范

如果你快有孩子了,出生前你比較急的一定是起個(gè)名字。孩子的姓名標(biāo)識(shí)著你和你愛人的血統(tǒng),一定不會(huì)起隔壁老王的姓氏,肯定會(huì)招來異樣的眼光。在maven中,groupId代表著姓氏,artifactId代表著名字。Spring Boot也是有一個(gè)命名的建議的。所以名字是不能夠隨隨便便取得,可以按照官方的建議來取。

What’s in a name All official starters follow a similar naming pattern; spring-boot-starter-*, where * is a particular type of application. This naming structure is intended to help when you need to find a starter. The Maven integration in many IDEs lets you search dependencies by name. For example, with the appropriate Eclipse or STS plugin installed, you can press ctrl-space in the POM editor and type “spring-boot-starter” for a complete list. As explained in the “Creating Your Own Starter” section, third party starters should not start with spring-boot, as it is reserved for official Spring Boot artifacts. Rather, a third-party starter typically starts with the name of the project. For example, a third-party starter project called thirdpartyproject would typically be named thirdpartyproject-spring-boot-starter.

大概意思是 官方的 starter 的命名格式為 spring-boot-starter-{xxxx} 比如spring-boot-starter-activemq第三方我們自己的命名格式為 {xxxx}-spring-boot-starter。比如mybatis-spring-boot-starter。如果我們忽略這種約定,是不是會(huì)顯得我們寫的東西不夠“專業(yè)“。

自定義一個(gè)Starter

下面我們就來實(shí)現(xiàn)一個(gè)自定義的發(fā)送短信的starter,命名為sms-spring-boot-starter

  1. 「引入pom
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
          <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>
  1. 「編寫配置文件」

發(fā)短信我們需要配置一些賬號(hào)信息,不同的短信供應(yīng)商,賬戶信息是不一樣的,所以我們需要定義一個(gè)XXXXProperties 來自動(dòng)裝配這些賬戶信息。下面我們就以騰訊云和阿里云兩家供應(yīng)商為例;

@ConfigurationProperties(prefix = "sms")
@Data
public class SmsProperties {

    private SmsMessage aliyun = new SmsMessage();

    private SmsMessage tencent = new SmsMessage();

    @Data
    public static class SmsMessage{


        /**
         * 用戶名
         */

        private String userName;

        /**
         * 密碼
         */

        private String passWord;

        /**
         * 秘鑰
         */

        private String sign;

        /**
         *
         */

        private String url;

        @Override
        public String toString() {
            return "SmsMessage{" +
                    "userName='" + userName + '\'' +
                    ", passWord='" + passWord + '\'' +
                    ", sign='" + sign + '\'' +
                    ", url='" + url + '\'' +
                    '}';
        }
    }
}

如果需要在其他項(xiàng)目中使用發(fā)送短信功能的話,我們只需要在配置文件(application.yml)中配置SmsProperties 的屬性信息就可以了。  比如:

sms:
  aliyun:
    pass-word: 12345
    user-name: java金融
    sign: 阿里云
    url: http://aliyun.com/send
  tencent:
    pass-word: 6666
    user-name: java金融
    sign: 騰訊云
    url: http://tencent.com/send

還記的@ConfigurationProperties注解里面是不是有個(gè)prefix 屬性,我們配置的這個(gè)屬性是sms,配置這個(gè)的主要一個(gè)作用的話是主要用來區(qū)別各個(gè)組件的參數(shù)。這里有個(gè)小知識(shí)點(diǎn)需要注意下當(dāng)我們?cè)谂渲梦募斎?code style="font-size: 14px;margin-right: 2px;margin-left: 2px;font-family: "Operator Mono", Consolas, Monaco, Menlo, monospace;word-break: break-all;color: rgb(53, 148, 247);background: rgba(59, 170, 250, 0.1);display: inline-block;padding-right: 2px;padding-left: 2px;border-radius: 2px;height: 21px;line-height: 22px;">sms我們的idea會(huì)提示這個(gè)sms有哪些屬性可以配置,以及每個(gè)屬性的注釋都有標(biāo)記,建議的話注釋還是寫英文,這樣會(huì)顯得你比較專業(yè)。保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter這個(gè)提示的話,是需要引入下面這個(gè)jar的。

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

引入這個(gè)jar之后,我們編譯之后就會(huì)在META-INF文件夾下面生成一個(gè)spring-configuration-metadata.json的文件。保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter我們可以看到這個(gè)文件其實(shí) 是根據(jù)SmsProperties類的成員屬性來生成的。

  1. 「然后在編寫短信自動(dòng)配置類:」
@EnableConfigurationProperties(value = SmsProperties.class)
@Configuration
public class SmsAutoConfiguration  {
    /**
     *  阿里云發(fā)送短信的實(shí)現(xiàn)類
     * @param smsProperties
     * @return
     */

    @Bean
    public AliyunSmsSenderImpl aliYunSmsSender(SmsProperties smsProperties){
       return new AliyunSmsSenderImpl(smsProperties.getAliyun());
    }
    /**
     * 騰訊云發(fā)送短信的實(shí)現(xiàn)類
     * @param smsProperties
     * @return
     */

    @Bean
    public TencentSmsSenderImpl tencentSmsSender(SmsProperties smsProperties){
        return new TencentSmsSenderImpl(smsProperties.getTencent());
    }
}

編寫我們的發(fā)送短信實(shí)現(xiàn)類:

public class AliyunSmsSenderImpl implements SmsSender {

    private SmsMessage smsMessage;

    public AliyunSmsSenderImpl(SmsMessage smsProperties) {
        this.smsMessage = smsProperties;
    }

    @Override
    public boolean send(String message) {
        System.out.println(smsMessage.toString()+"開始發(fā)送短信==》短信內(nèi)容:"+message);
        return true;
    }
}
  1. 「讓starter生效」

starter集成應(yīng)用有兩種方式:

  • 被動(dòng)生效 我們首先來看下我們熟悉的方式,通過 SpringBootSPI的機(jī)制來去加載我們的starter。我們需要在 META-INF下新建一個(gè) spring.factories文件 keyorg.springframework.boot.autoconfigure.EnableAutoConfiguration, value是我們的 SmsAutoConfiguration 全限定名( 「記得去除前后的空格,否則會(huì)不生效」)。 保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter
  • 主動(dòng)生效 在 starter組件集成到我們的 Spring Boot應(yīng)用時(shí)需要主動(dòng)聲明啟用該 starter才生效,通過自定義一個(gè) @Enable注解然后在把自動(dòng)配置類通過 Import注解引入進(jìn)來。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import({SmsAutoConfiguration.class})
public @interface EnableSms {
}

使用的時(shí)候需要在啟動(dòng)類上面開啟這個(gè)注解。保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter5.「打包,部署到倉(cāng)庫(kù)」如果是本地的話,直接通過mvn install命令就可以了。如果需要部署到公司的倉(cāng)庫(kù)話,這個(gè)就不說了。6. 「新建一個(gè)新的SpringBoot項(xiàng)目引入我們剛寫的starter

 <dependency>
            <groupId>com.workit.sms</groupId>
            <artifactId>sms-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
      </dependency>

在項(xiàng)目配置文件配上短信賬號(hào)信息保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter測(cè)試代碼

@SpringBootApplication
@EnableSms
public class AutoconfigApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(AutoconfigApplication.class, args);
        AliyunSmsSenderImpl aliyunSmsSender = applicationContext.getBean(AliyunSmsSenderImpl.class);
        aliyunSmsSender.send("用阿里云發(fā)送短信");
        TencentSmsSenderImpl tencentSmsSender = applicationContext.getBean(TencentSmsSenderImpl.class);
        tencentSmsSender.send("用騰訊云發(fā)送短信");
    }

運(yùn)行結(jié)果:

SmsMessage{userName='java金融', passWord='12345', sign='阿里云', url='http://aliyun.com/send'}開始發(fā)送短信==》短信內(nèi)容:用阿里云發(fā)送短信
SmsMessage{userName='java金融', passWord='6666', sign='騰訊云', url='http://tencent.com/send'}開始發(fā)送短信==》短信內(nèi)容:用騰訊云發(fā)送短信

至此的話我們自定義的一個(gè)starter就已經(jīng)完成了,這個(gè)starter只是一個(gè)演示的demo,代碼有點(diǎn)粗糙,項(xiàng)目結(jié)構(gòu)也有點(diǎn)問題。重點(diǎn)看下這個(gè)實(shí)現(xiàn)原理就好。趕緊動(dòng)動(dòng)小手去實(shí)現(xiàn)一個(gè)自己的starter吧。

總結(jié)

  • SpringBoot starter的出現(xiàn),讓我們項(xiàng)目中集成其他組件變得簡(jiǎn)單。它把簡(jiǎn)單給了別人,把復(fù)雜留給了自己?!盃奚∥遥删痛笪摇钡乃枷脒€是值得學(xué)習(xí)的。平時(shí)我們工作中,比如要開發(fā)一個(gè)組件、或者一個(gè)工具類,也應(yīng)該盡可能的讓使用方可以做到無腦使用,不要搞的太復(fù)雜,又能讓使用者可以靈活擴(kuò)展。
  • 站在巨人的肩膀上摘蘋果:
    https://docs.spring.io/spring-boot/docs/2.3.2.RELEASE/reference/htmlsingle/

    https://www.cnblogs.com/tjudzj/p/8758391.html https://blog.springlearn.cn/psts/14644/



  • 特別推薦一個(gè)分享架構(gòu)+算法的優(yōu)質(zhì)內(nèi)容,還沒關(guān)注的小伙伴,可以長(zhǎng)按關(guān)注一下:

    保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter

    保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter

  • 保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter

  • 長(zhǎng)按訂閱更多精彩▼

    保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter

    如有收獲,點(diǎn)個(gè)在看,誠(chéng)摯感謝

免責(zé)聲明:本文內(nèi)容由21ic獲得授權(quán)后發(fā)布,版權(quán)歸原作者所有,本平臺(tái)僅提供信息存儲(chǔ)服務(wù)。文章僅代表作者個(gè)人觀點(diǎn),不代表本平臺(tái)立場(chǎng),如有問題,請(qǐng)聯(lián)系我們,謝謝!

本站聲明: 本文章由作者或相關(guān)機(jī)構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點(diǎn),本站亦不保證或承諾內(nèi)容真實(shí)性等。需要轉(zhuǎn)載請(qǐng)聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請(qǐng)及時(shí)聯(lián)系本站刪除。
換一批
延伸閱讀

9月2日消息,不造車的華為或?qū)⒋呱龈蟮莫?dú)角獸公司,隨著阿維塔和賽力斯的入局,華為引望愈發(fā)顯得引人矚目。

關(guān)鍵字: 阿維塔 塞力斯 華為

倫敦2024年8月29日 /美通社/ -- 英國(guó)汽車技術(shù)公司SODA.Auto推出其旗艦產(chǎn)品SODA V,這是全球首款涵蓋汽車工程師從創(chuàng)意到認(rèn)證的所有需求的工具,可用于創(chuàng)建軟件定義汽車。 SODA V工具的開發(fā)耗時(shí)1.5...

關(guān)鍵字: 汽車 人工智能 智能驅(qū)動(dòng) BSP

北京2024年8月28日 /美通社/ -- 越來越多用戶希望企業(yè)業(yè)務(wù)能7×24不間斷運(yùn)行,同時(shí)企業(yè)卻面臨越來越多業(yè)務(wù)中斷的風(fēng)險(xiǎn),如企業(yè)系統(tǒng)復(fù)雜性的增加,頻繁的功能更新和發(fā)布等。如何確保業(yè)務(wù)連續(xù)性,提升韌性,成...

關(guān)鍵字: 亞馬遜 解密 控制平面 BSP

8月30日消息,據(jù)媒體報(bào)道,騰訊和網(wǎng)易近期正在縮減他們對(duì)日本游戲市場(chǎng)的投資。

關(guān)鍵字: 騰訊 編碼器 CPU

8月28日消息,今天上午,2024中國(guó)國(guó)際大數(shù)據(jù)產(chǎn)業(yè)博覽會(huì)開幕式在貴陽(yáng)舉行,華為董事、質(zhì)量流程IT總裁陶景文發(fā)表了演講。

關(guān)鍵字: 華為 12nm EDA 半導(dǎo)體

8月28日消息,在2024中國(guó)國(guó)際大數(shù)據(jù)產(chǎn)業(yè)博覽會(huì)上,華為常務(wù)董事、華為云CEO張平安發(fā)表演講稱,數(shù)字世界的話語(yǔ)權(quán)最終是由生態(tài)的繁榮決定的。

關(guān)鍵字: 華為 12nm 手機(jī) 衛(wèi)星通信

要點(diǎn): 有效應(yīng)對(duì)環(huán)境變化,經(jīng)營(yíng)業(yè)績(jī)穩(wěn)中有升 落實(shí)提質(zhì)增效舉措,毛利潤(rùn)率延續(xù)升勢(shì) 戰(zhàn)略布局成效顯著,戰(zhàn)新業(yè)務(wù)引領(lǐng)增長(zhǎng) 以科技創(chuàng)新為引領(lǐng),提升企業(yè)核心競(jìng)爭(zhēng)力 堅(jiān)持高質(zhì)量發(fā)展策略,塑強(qiáng)核心競(jìng)爭(zhēng)優(yōu)勢(shì)...

關(guān)鍵字: 通信 BSP 電信運(yùn)營(yíng)商 數(shù)字經(jīng)濟(jì)

北京2024年8月27日 /美通社/ -- 8月21日,由中央廣播電視總臺(tái)與中國(guó)電影電視技術(shù)學(xué)會(huì)聯(lián)合牽頭組建的NVI技術(shù)創(chuàng)新聯(lián)盟在BIRTV2024超高清全產(chǎn)業(yè)鏈發(fā)展研討會(huì)上宣布正式成立。 活動(dòng)現(xiàn)場(chǎng) NVI技術(shù)創(chuàng)新聯(lián)...

關(guān)鍵字: VI 傳輸協(xié)議 音頻 BSP

北京2024年8月27日 /美通社/ -- 在8月23日舉辦的2024年長(zhǎng)三角生態(tài)綠色一體化發(fā)展示范區(qū)聯(lián)合招商會(huì)上,軟通動(dòng)力信息技術(shù)(集團(tuán))股份有限公司(以下簡(jiǎn)稱"軟通動(dòng)力")與長(zhǎng)三角投資(上海)有限...

關(guān)鍵字: BSP 信息技術(shù)
關(guān)閉
關(guān)閉