作者: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下的文件和文件夹

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插件,将项目打包安装到本地仓库

新建测试项目,引入我们自己的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. 多线程内容聚合

如何使用SpringBoot封装自己的Starter的更多相关文章

  1. SpringBoot封装自己的Starter

    https://juejin.im/post/5cb880c2f265da03981fc031 一.说明 我们在使用SpringBoot的时候常常要引入一些Starter,例如spring-boot- ...

  2. SpringBoot起飞系列-自定义starter(十)

    一.前言 到现在,我们可以看出来,如果我们想用一些功能,基本上都是通过添加spring-boot-starter的方式来使用的,因为各种各样的功能都被封装成了starter,然后把相关服务注入到容器中 ...

  3. springboot封装JsonUtil,CookieUtil工具类

    springboot封装JsonUtil,CookieUtil工具类 yls 2019-9-23 JsonUtil public class JsonUtil { private static Obj ...

  4. SpringBoot系列之自定义starter实践教程

    SpringBoot系列之自定义starter实践教程 Springboot是有提供了很多starter的,starter翻译过来可以理解为场景启动器,所谓场景启动器配置了自动配置等等对应业务模块的一 ...

  5. 深入springboot原理——一步步分析springboot启动机制(starter机制)

    前言 使用过springboot的同学应该已经知道,springboot通过默认配置了很多框架的使用方式帮我们大大简化了项目初始搭建以及开发过程.本文的目的就是一步步分析springboot的启动过程 ...

  6. SpringBoot原理—分析SpringBoot启动机制(starter机制)

    一:前言使用过springboot的同学应该已经知道,springboot通过默认配置了很多框架的使用方式帮我们大大简化了项目初始搭建以及开发过程.本文的目的就是一步步分析springboot的启动过 ...

  7. SpringBoot 系列 - 自己写starter

    原文地址: https://www.xncoding.com/2017/07/22/spring/sb-starter.html 前言: Spring Boot由众多Starter组成,随着版本的推移 ...

  8. SpringBoot编写自定义的starter 专题

    What’s in a name All official starters follow a similar naming pattern; spring-boot-starter-*, where ...

  9. SpringBoot四大神器之Starter

    SpringBoot的starter主要用来简化依赖用的.本文主要分两部分,一部分是列出一些starter的依赖,另一部分是教你自己写一个starter. 部分starters的依赖 Starter( ...

随机推荐

  1. 手动启动Oracle服务的.bat文件

    Oracle数据库的基本服务会占用很大的内存,有的程序员会在不用的时候Oracle服务关闭来减少对电脑内存资源的占用. 我在这准备了一个可以开启/关闭Oracle服务的bat文件,希望被采纳!!! 新 ...

  2. 字符串的扩展(ES6)

    文章目录 字符串的扩展 1. 字符的Unicode表示法 2. codePointAt() 3. String.fromCodePoint() 4. 字符串的遍历器接口 5. at()(提案) 6. ...

  3. 如何入侵SF服务器/充当GM刷元宝

    首要作者本人要声明一下,写下此文章技术不是教你去黑传奇SF,只是想以本文引起4F拥有者的留意方案,哈哈. 如何入侵传奇SF刷元宝,首先要温故下自己的专业技术水平. 我也非常喜欢玩游戏,但却玩得特别菜, ...

  4. 调用高德API,通过输入的地址,如省份、市、区获取经纬度 ,通过输入的经纬度,获取区域详情

    一.pom <?xml version="1.0" encoding="UTF-8"?><projectxmlns="http:// ...

  5. Android设置EditText不可编辑

    版权声明:本文为xing_star原创文章,转载请注明出处! 本文同步自http://javaexception.com/archives/224 禁用EditText 这个其实很简单,最简单的一种方 ...

  6. MSSQL - 最佳实践 - 使用SSL加密连接

    MSSQL - 最佳实践 - 使用SSL加密连接 author: 风移 摘要 在SQL Server安全系列专题月报分享中,往期我们已经陆续分享了:如何使用对称密钥实现SQL Server列加密技术. ...

  7. MTDDL 美团分布式数据访问中间件(转)

    MTDDL 美团分布式数据访问中间件(转) 原文地址:MTDDL--美团点评分布式数据访问层中间件 因原文文字和图显示有问题,故整理于此,仅供参考. 业界方案 组件 简介 Atlas Qihoo 36 ...

  8. 熔断器Hystrix及服务监控Dashboard

    服务雪崩效应 当一个请求依赖多个服务的时候: 正常情况下的访问 : 但是,当请求的服务中出现无法访问.异常.超时等问题时(图中的I),那么用户的请求将会被阻塞. 如果多个用户的请求中,都存在无法访问的 ...

  9. 微信小程序的入门

    1.申请账号     官网:https://mp.weixin.qq.com/  2.开发工具      为了帮助开发者简单和高效地开发和调试微信小程序,推出了小程序开发者工具,集成了公众号网页调试和 ...

  10. 中国古风唯美水墨工作计划汇报PPT模板推荐

    模版来源:http://ppt.dede58.com/