How to use SpringBoot own Starter Package

Author: Sans_

juejin.im/post/5cb880c2f265da03981fc031

I. Description

When we use SpringBoot often to introduce Starter, such as spring-boot-starter-web, almost all of the official default configuration for us, a good reduces the complexity when using frames.

So when a xxx-starter, you can not bother to write some tedious configuration files, configuration even necessary configuration application.properties or application.yml on it, when you achieve a Starter, you can be in different projects multiplexing, very convenient, and today we come to write your own Starter before the SMS service as an example.

Reference: https: //juejin.im/post/5cb165486fb9a068a60c2827

spring-boot-starter-xxx is the official naming Starter, Starter unofficial naming the official recommendations for xxx-spring-boot-starter

II. Building project

Establish SpringBoot project, under the resources to clear files and folders

How to use SpringBoot own Starter Package

Maven dependency follows:

 <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 is not necessary, its role is to generate and compile-time spring-configuration-metadata.json, this document primarily for use IDEA.

This configuration JAR-related configuration properties in application.yml, you can use Ctrl + left mouse button click the attribute name, IDE will jump you to configure this property in the class, and will write application.yml code hints.

III. The preparation of project-based class

Create SendSMSDTO transmission type, transmission parameters for

/**
 * 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;
}

Creating RestTemplateConfig configuration class, used to call short message interface

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

Create a text interface to enumerate classes for storing address SMS interface (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;
    }
}

IV. Starter write the automatic configuration class

Create SmsProperties attribute classes, class is mainly used to read yml / properties Information

/**
 * 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;
}

Create a text service core classes

/**
 * 短信核心服务类
 * @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;
    }
}

Creating SmsAutoConfiguration automatic configuration class, which is mainly used to create the core business class instance

/**
 * 短信自动配置类
 * @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;
    }
}

V. Create a file spring.factories

spring.factories the automatic configuration file used to define classes, SpringBoot will be started when the object is instantiated, the configuration file is loaded by loading class SpringFactoriesLoader, the file is loaded in the configuration class spring containers
in src / main / resources New META-INF folder, create a new file in spring.factories META-INF folder. Configuration reads as follows:

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

VI. Packaging and Testing

Using Maven plug-ins, project installation package to a local warehouse

How to use SpringBoot own Starter Package

New Test Project, the introduction of our own Starter, Maven relies as follows:

<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>

Configuring test project application.yml

sms-config:
  account-sid:  //这里填写平台获取的ID和KEY
  auth-token:   //这里填写平台获取的ID和KEY
  appid:        //这里填写平台获取的ID和KEY

Parameters fill in their phone number and application templates and corresponding parameters

/**
 * 测试短信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);
    }
}

Project Source:

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

 

Recommended reading (click to jump to read)

1.  SpringBoot content aggregator

2.  face questions content aggregator

3. The  design pattern content aggregator

4.  Mybatis content aggregator

The  multithreaded content aggregator

Guess you like

Origin www.cnblogs.com/javazhiyin/p/11390355.html