如何使用SpringBoot封裝自己的Starter


作者:Sans_

juejin.im/post/5cb880c2f265da03981fc031

一.說明

我們在使用SpringBoot的時候常常要引入一些Starter,例如spring-boot-starter-web,官方為我們提供了幾乎所有的默認配置,很好的降低了使用框架時的復雜度。

所以在用xxx-starter的時候,可以不用費心去寫一些繁瑣的配置文件,即使必要的配置在application.properties或application.yml中配置就可以了,當你實現了一個Starter,可以在不同的項目中復用,非常方便,今天我們來編寫自己的Starter以之前的短信業務為例。

參考:https://juejin.im/post/5cb165486fb9a068a60c2827

spring-boot-starter-xxx是官方提供Starter的命名規則,非官方Starter的命名規則官方建議為 xxx-spring-boot-starter

二.搭建項目

建立SpringBoot項目,清除resources下的文件和文件夾

如何使用SpringBoot封裝自己的Starter

Maven依賴如下:

 <dependencies>
        <!--封裝Starter核心依賴  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <!--非必需,該依賴作用是在使用IDEA編寫配置文件有代碼提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <!-- lombok 插件  -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <optional>true</optional>
        </dependency>
        <!-- 因為要使用RestTemplate和轉換Json,所以引入這兩個依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.45</version>
        </dependency>
</dependencies>

spring-boot-configuration-processor不是必須的,它的作用是和編譯時生成 spring-configuration-metadata.json,此文件主要給IDEA使用。

配置此JAR相關配置屬性在 application.yml中,你可以用Ctrl+鼠標左鍵點擊屬性名,IDE會跳轉到你配置此屬性的類中,並且編寫application.yml會有代碼提示。

三.編寫項目基礎類

創建SendSMSDTO傳輸類,用於參數傳遞

/**
 * SMSDTO參數類
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@Data
public class SendSMSDTO {
    /**
     * 模板ID
     */
    private String templateid;
    /**
     * 參數
     */
    private String param;
    /**
     * 手機號
     */
    private String mobile;
    /**
     * 用戶穿透ID,可以為空
     */
    private String uid;
}

創建RestTemplateConfig配置類,用於調用短信接口

/**
 * RestTemplateConfig配置
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate( ) {
        return new RestTemplate();
    }
}

創建短信接口枚舉類,用於存放短信接口API地址

/**
 * 短信請求API枚舉
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@Getter
public enum ENUM_SMSAPI_URL {
    SENDSMS("https://open.ucpaas.com/ol/sms/sendsms"),
    SENDBATCHSMS("https://open.ucpaas.com/ol/sms/sendsms_batch");
    private String url;
    ENUM_SMSAPI_URL(String url) {
        this.url = url;
    }
}

四.編寫Starter自動配置類

創建SmsProperties配置屬性類,該類主要用於讀取yml/properties信息

/**
 * SMS配置屬性類
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention 使用ConfigurationProperties注解可將配置文件(yml/properties)中指定前綴的配置轉為bean
 */
@Data
@ConfigurationProperties(prefix = "sms-config")
public class SmsProperties {
    private String appid;
    private String accountSid;
    private String authToken;
}

創建短信核心服務類

/**
 * 短信核心服務類
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
public class SmsService {

    @Autowired
    private RestTemplate restTemplate;
    private String appid;
    private String accountSid;
    private String authToken;

    /**
     * 初始化
     */
    public SmsService(SmsProperties smsProperties) {
       this.appid = smsProperties.getAppid();
       this.accountSid = smsProperties.getAccountSid();
       this.authToken = smsProperties.getAuthToken();
    }

    /**
     * 單獨發送
     */
    public String sendSMS(SendSMSDTO sendSMSDTO){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sid", accountSid);
        jsonObject.put("token", authToken);
        jsonObject.put("appid", appid);
        jsonObject.put("templateid", sendSMSDTO.getTemplateid());
        jsonObject.put("param", sendSMSDTO.getParam());
        jsonObject.put("mobile", sendSMSDTO.getMobile());
        if (sendSMSDTO.getUid()!=null){
            jsonObject.put("uid",sendSMSDTO.getUid());
        }else {
            jsonObject.put("uid","");
        }
        String json = JSONObject.toJSONString(jsonObject);
        //使用restTemplate進行訪問遠程Http服務
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
        String result = restTemplate.postForObject(ENUM_SMSAPI_URL.SENDSMS.getUrl(), httpEntity, String.class);
        return result;
    }

    /**
     * 群體發送
     */
    public String sendBatchSMS(SendSMSDTO sendSMSDTO){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sid", accountSid);
        jsonObject.put("token", authToken);
        jsonObject.put("appid", appid);
        jsonObject.put("templateid", sendSMSDTO.getTemplateid());
        jsonObject.put("param", sendSMSDTO.getParam());
        jsonObject.put("mobile", sendSMSDTO.getMobile());
        if (sendSMSDTO.getUid()!=null){
            jsonObject.put("uid",sendSMSDTO.getUid());
        }else {
            jsonObject.put("uid","");
        }
        String json = JSONObject.toJSONString(jsonObject);
        //使用restTemplate進行訪問遠程Http服務
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
        String result = restTemplate.postForObject(ENUM_SMSAPI_URL.SENDBATCHSMS.getUrl(), httpEntity, String.class);
        return result;
    }
}

創建SmsAutoConfiguration自動配置類,該類主要用於創建核心業務類實例

/**
 * 短信自動配置類
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@Configuration  
@EnableConfigurationProperties(SmsProperties.class)//使@ConfigurationProperties注解生效
public class SmsAutoConfiguration {
    @Bean
    public SmsService getBean(SmsProperties smsProperties){
        SmsService smsService = new SmsService(smsProperties);
        return smsService;
    }
}

五.創建spring.factories文件

spring.factories該文件用來定義需要自動配置的類,SpringBoot啟動時會進行對象的實例化,會通過加載類SpringFactoriesLoader加載該配置文件,將文件中的配置類加載到spring容器
在src/main/resources新建META-INF文件夾,在META-INF文件夾下新建spring.factories文件。配置內容如下:

 org.springframework.boot.autoconfigure.EnableAutoConfiguration=
        com.sms.starter.config.SmsAutoConfiguration

六.打包和測試

使用Maven插件,將項目打包安裝到本地倉庫

如何使用SpringBoot封裝自己的Starter

新建測試項目,引入我們自己的Starter,Maven依賴如下:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- 添加我們自己的starter-->
        <dependency>
            <groupId>com.sms.starter</groupId>
            <artifactId>sms-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
</dependencies>

配置測試項目的application.yml

sms-config:
  account-sid:  //這里填寫平台獲取的ID和KEY
  auth-token:   //這里填寫平台獲取的ID和KEY
  appid:        //這里填寫平台獲取的ID和KEY

參數填寫自己的手機號和申請的模板以及對應的參數

/**
 * 測試短信DEMO
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@RestController
@RequestMapping("/sms")
public class TestController {
    @Autowired
    private SmsService smsService;
    /**
     * 短信測試
     * @Attention
     * @Author: Sans
     * @CreateTime: 2019/4/20 
     */
    @RequestMapping(value = "/sendsmsTest",method = RequestMethod.GET)
    public String sendsmsTest(){
        //創建傳輸類設置參數
        SendSMSDTO sendSMSDTO  = new SendSMSDTO();
        sendSMSDTO.setMobile("");     //手機號
        sendSMSDTO.setTemplateid(""); //模板
        sendSMSDTO.setParam("");      //參數
        return smsService.sendSMS(sendSMSDTO);
    }
}

項目源碼:

https://gitee.com/liselotte/sms-spring-boot-starter

 

推薦閱讀(點擊即可跳轉閱讀)

1. SpringBoot內容聚合

2. 面試題內容聚合

3. 設計模式內容聚合

4. Mybatis內容聚合

5. 多線程內容聚合


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM