保姆級(jí)教程,手把手教你實(shí)現(xiàn)一個(gè)SpringBoot的starter
引言
什么是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
了)。
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-startersstarter
的實(shí)現(xiàn):雖然我們每個(gè)組件的starter
實(shí)現(xiàn)各有差異,但是它們基本上都會(huì)使用到兩個(gè)相同的內(nèi)容:ConfigurationProperties
和AutoConfiguration
。因?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ì)生效。除此之外,starter
的ConfigurationProperties
還使得所有的配置屬性被聚集到一個(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
。
-
「引入 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>
-
「編寫配置文件」
發(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è)。這個(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
的文件。我們可以看到這個(gè)文件其實(shí) 是根據(jù)SmsProperties類的成員屬性來生成的。
-
「然后在編寫短信自動(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;
}
}
-
「讓starter生效」
starter
集成應(yīng)用有兩種方式:
-
被動(dòng)生效 我們首先來看下我們熟悉的方式,通過 SpringBoot
的SPI
的機(jī)制來去加載我們的starter。我們需要在META-INF
下新建一個(gè)spring.factories
文件key
為org.springframework.boot.autoconfigure.EnableAutoConfiguration, value
是我們的SmsAutoConfiguration
全限定名( 「記得去除前后的空格,否則會(huì)不生效」)。 -
主動(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è)注解。5.「打包,部署到倉(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)信息測(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)注一下:
長(zhǎng)按訂閱更多精彩▼
如有收獲,點(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)系我們,謝謝!