How to use SpringBoot to encapsulate your Starter

Posted by Vasudhevan on Wed, 21 Aug 2019 12:46:41 +0200

Authors: Sans_

juejin.im/post/5cb880c2f265da03981fc031

I. Explanation

When we use SpringBoot, we often introduce some Starters, such as spring-boot-starter-web. Officials provide us with almost all default configurations, which greatly reduces the complexity of using the framework.

So when using xxx-starter, you can not bother to write some tedious configuration files, even if the necessary configuration is configurated in application.properties or application.yml. When you implement a Starter, you can reuse it in different projects. It is very convenient. Today we will write our own Starter to Previous short message service as an example.

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

Spr-boot-starter-xxx is the official naming rule for Starter. The official recommendation for unofficial Starter is xxx-spring-boot-starter.

II. Building Projects

Create SpringBook project to clear files and folders under resources

Maven relies on the following:

 <dependencies>
        <!--encapsulation Starter Core dependence  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <!--Non-essential,This dependency is in use IDEA Write configuration files with code hints-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <!-- lombok Plug-in unit  -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <optional>true</optional>
        </dependency>
        <!-- Because to use RestTemplate And Conversion Json,So introduce these two dependencies -->
        <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>

Spr-boot-configuration-processor is not necessary. Its function is to generate spring-configuration-metadata.json at compilation time. This file is mainly used by IDEA.

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

III. Writing the Basic Categories of Projects

Create SendSMSDTO transport class for parameter passing

/**
 * SMSDTO Parametric class
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@Data
public class SendSMSDTO {
    /**
     * Template ID
     */
    private String templateid;
    /**
     * parameter
     */
    private String param;
    /**
     * Cell-phone number
     */
    private String mobile;
    /**
     * Users can penetrate the ID and can be null
     */
    private String uid;
}

Create RestTemplateConfig configuration class for calling SMS interface

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

Create an SMS interface enumeration class to store the SMS interface API address

/**
 * Enumeration of SMS Request 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. Writing Starter Autoconfiguration Class

Create SmsProperties configuration property class, which is mainly used to read yml/properties information

/**
 * SMS Configuration attribute class
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention Using the Configuration Properties annotation, you can convert the configuration of the specified prefix in the configuration file (yml/properties) to a bean
 */
@Data
@ConfigurationProperties(prefix = "sms-config")
public class SmsProperties {
    private String appid;
    private String accountSid;
    private String authToken;
}

Creating the core service class of short message

/**
 * Short Message Core Service Class
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
public class SmsService {

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

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

    /**
     * Send separately
     */
    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);
        //Accessing remote Http services using restTemplate
        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;
    }

    /**
     * Group Sending
     */
    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);
        //Accessing remote Http services using restTemplate
        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;
    }
}

Create SmsAutoConfiguration Automatic Configuration Class, which is mainly used to create core business class instances

/**
 * Short Message Automatic Configuration Class
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@Configuration  
@EnableConfigurationProperties(SmsProperties.class)//Make the @Configuration Properties annotation effective
public class SmsAutoConfiguration {
    @Bean
    public SmsService getBean(SmsProperties smsProperties){
        SmsService smsService = new SmsService(smsProperties);
        return smsService;
    }
}

5. Create spring.factories file

spring.factories is a file that defines classes that need to be automatically configured. SpringBoot Objects are instantiated at startup, and the configuration file is loaded by loading the class SpringFactories Loader, which loads the configuration class in the file into the spring container.
New META-INF folder in src/main/resources and new spring.factories file in META-INF folder. The configuration is as follows:

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

Packaging and testing

Use the Maven plug-in to package and install the project into the local warehouse

New test projects, introducing our own Starter, Maven relies on the following:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Add our own starter-->
        <dependency>
            <groupId>com.sms.starter</groupId>
            <artifactId>sms-spring-boot-starter</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
</dependencies>

Configure the application.yml of the test project

sms-config:
  account-sid:  //Here, fill in the ID and KEY obtained by the platform.
  auth-token:   //Here, fill in the ID and KEY obtained by the platform.
  appid:        //Here, fill in the ID and KEY obtained by the platform.

Fill in your cell phone number, application template and corresponding parameters

/**
 * Test SMS DEMO
 * @Author Sans
 * @CreateTime 2019/4/20 
 * @attention
 */
@RestController
@RequestMapping("/sms")
public class TestController {
    @Autowired
    private SmsService smsService;
    /**
     * Short Message Testing
     * @Attention
     * @Author: Sans
     * @CreateTime: 2019/4/20 
     */
    @RequestMapping(value = "/sendsmsTest",method = RequestMethod.GET)
    public String sendsmsTest(){
        //Create transport class settings parameters
        SendSMSDTO sendSMSDTO  = new SendSMSDTO();
        sendSMSDTO.setMobile("");     //Cell-phone number
        sendSMSDTO.setTemplateid(""); //Template
        sendSMSDTO.setParam("");      //parameter
        return smsService.sendSMS(sendSMSDTO);
    }
}

Project source code:

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

 

Recommended reading (click to skip reading)

1. SpringBook content aggregation

2. Content aggregation of interview questions

3. Design pattern content aggregation

4. Mybatis content aggregation

5. Multithread Content Aggregation

Topics: Java Spring JSON Maven Mobile