[Case combat] SpringBoot3.x custom package starter combat

1. Background introduction and function of starter

(1) What is a starter

starter is a new invention in SpringBoot, which effectively reduces the complexity of the project development process and has a very good effect on simplifying development operations.

The concept of the starter: the starter will include all the dependencies used, avoiding the trouble caused by the developers themselves introducing dependencies. It should be noted that different starters are used to solve different dependencies, so their internal implementation may be very different. For example, the starter of jpa and the starter of Redis may have different implementations, because the essence of the starter lies in the synthesize , which is a layer of abstraction at the logical level. Perhaps this concept is somewhat similar to Docker, because they are all doing a "packaging" operation. If you know what problem Docker is designed to solve, maybe you can use Docker Make an analogy with starter.

(2) Customize the background of the starter

  • Everyone should have used a lot of Starters, and there are many middlewares, but there are also many middlewares that lack Starters or are incompatible.
  • For example, if the Spring Boot 3.x version is updated, some Starters have not had time to update, so they cannot be used.
  • The technical team leader or architect in the actual enterprise will also
  • Encapsulate the Starter of your own project group to achieve faster development projects, and can be unified and standardized to simplify configuration

(3) Customize the Starter package specification

  • Official Starter package specification: spring-boot-starter-xxx
  • Custom Starter package specification: xxx-spring-boot-starter
spring-boot-starter
spring-boot-starter-data-jpa
spring-boot-starter-data-redis
spring-boot-starter-data-mongodb
spring-boot-starter-jdbc
mybatis-spring-boot-starter
mybatis-plus-boot-starter

(4) The difference between the new version of Spring Boot3.X and the custom Starter before the old version of SpringBoot2.7

  • Before SpringBoot2.7

    • Add in the META-INF/spring.factories fileorg.springframework.boot.autoconfigure.EnableAutoConfiguration=XXAutoConfiguration
    • I will use another article to show the custom starter before springboot2.7. Here will be updated later!

    insert image description here

  • SpringBoot2.7 introduces new automatic configuration

    • 在META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
    • Add the name of the configuration class to the file, each line contains a fully qualified name of the configuration class
    • Compatible with META-INF/spring.factories method
  • SpringBoot3.x removes spring.factories

    • Remove META-INF/spring.factories way
    • Only support META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports Add automatic configuration

2. Steps to customize the starter

  • Create project xx-spring-boot-starter

  • add dependencies

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>3.0.2</version>
</dependency>

  • Create a configuration class
  • Create the XXAutoConfiguration class
  • Add Condition condition annotation
  • Configure AutoConfiguration.imports auto-configuration class

3. Customize the starter case in practice

(1) Demand background

  • Now all the SMS sending of the company is integrated into the message center. In order to simplify the development of each platform, a sms-starter is customized and packaged for each platform to use.
  • Customize a sms-starter for sending text messages. The starter is connected to various three-party SMS platforms, such as Alibaba Cloud, Tencent Cloud, and Amazon Cloud. Developers can configure the SMS provider according to the configuration. The default provider is Alibaba Cloud.
  • If the Spring container does not have a corresponding bean, it will be created, and if there is, it will not be created.

(2) Create SpringBoot3.x project sms-spring-boot-starter, add autoconfigure dependency

insert image description here

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>3.0.2</version>
        </dependency>

(3) Create a configuration class and bind the application.yml configuration file through the @ConfigurationProperties annotation

  • Create a type enumeration class for SMS operators
public enum SmsTypeEnum {
    
    
		//阿里云
    ALI_CLOUD("ali"),
  	//腾讯云
    TX_CLOUD("tx"),
  	//亚马逊云
    YMX_CLOUD("ymx");

    private String type;

    SmsTypeEnum(String ymx) {
    
    }

}
@ConfigurationProperties(prefix = "sms.server.achieve")
public class SmsProperties {
    
    
		
  	/**
   	 * 发送短信类型
   	 */
    private String type;

    public String getType() {
    
    
        if(type == null || "".equals(type)){
    
    
            type = SmsTypeEnum.ALI_YUN.name();
        }
        return type;
    }

    public void setType(String type) {
    
    
        this.type = type;
    }
}

(4) Create the SmsService interface and encapsulate the implementation of sending SMS of the three cloud vendors.

public interface SmsService {
    
    
    String send(String fromPhone,String toPhone,String content);
}
/**
 * 阿里云SMS实现
 * @author lixiang
 * @date 2023/5/16 09:30
 */
@Service("ali")
public class AliCloudSmsServiceImpl implements SmsService {
    
    

    @Override
    public String send(String fromPhone, String toPhone, String content) {
    
    
        System.out.println("------------------当前SMS厂商为阿里云------------------");
        System.out.println("----"+fromPhone+" 向 "+toPhone +" 发送了一条短信。"+"----");
        System.out.println("短信内容为:"+content);
        System.out.println("----------------------------------------------------");
        return "success";
    }
}
/**
 * 腾讯云SMS实现
 * @author lixiang
 * @date 2023/5/16 09:44
 */
@Service("tx")
public class TxCloudSmsServiceImpl implements SmsService {
    
    
    @Override
    public String send(String fromPhone, String toPhone, String content) {
    
    
        System.out.println("------------------当前SMS厂商为腾讯云------------------");
        System.out.println("----"+fromPhone+" 向 "+toPhone +" 发送了一条短信。"+"----");
        System.out.println("短信内容为:"+content);
        System.out.println("----------------------------------------------------");
        return "success";
    }
}
/**
 * 亚马逊云SMS实现
 * @author lixiang
 * @date 2023/5/16 09:42
 */
@Service("ymx")
public class YmxCloudSmsServiceImpl implements SmsService {
    
    
    @Override
    public String send(String fromPhone, String toPhone, String content) {
    
    
        System.out.println("------------------当前SMS厂商为亚马逊云------------------");
        System.out.println("----"+fromPhone+" 向 "+toPhone +" 发送了一条短信。"+"----");
        System.out.println("短信内容为:"+content);
        System.out.println("----------------------------------------------------");
        return "success";
    }
}

(5) Define SmsTemplate for unified service provision

/**
 * @author lixiang
 * @date 2023/5/16 09:33
 */
public class SmsTemplate {
    
    

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private ApplicationContext context;

    public String send(String fromPhone,String toPhone,String content){
    
    
        //获取云厂商的业务实现类
        String type = smsProperties.getType();
        SmsService smsService = (SmsService)context.getBean(type);
        return smsService.send(fromPhone,toPhone,content);
    }
}

(6) Define the SmsAutoConfiguration class

/**
 * @author lixiang
 * @date 2023/5/16 09:27
 */
@AutoConfiguration
@ConditionalOnClass(SmsTemplate.class)
@EnableConfigurationProperties(value = SmsProperties.class)
public class SmsAutoConfiguration {
    
    

    @Bean
    @ConditionalOnMissingBean
    public SmsTemplate smsTemplate(){
    
    
        return new SmsTemplate();
    }

}

(7) Create an imports configuration file and configure the classes that need to be automatically loaded.

  • @AutoConfiguration is newly introduced by spring boot 2.7. The automatic configuration class must be placed in the following file to be considered an automatic configuration class
  • META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

insert image description here

com.lixiang.config.SmsAutoConfiguration

(8) mvn clean install into the local warehouse

insert image description here

4. Verify custom starter

(1) To create a new project, pay attention to the version above springboot3.x.

        <dependency>
            <groupId>com.lixiang</groupId>
            <artifactId>sms-spring-boot-starter</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

(2) Create test code

@RestController
@RequestMapping("/spring-test")
public class TestController {
    
    

    @Autowired
    private SmsTemplate smsTemplate;

    @RequestMapping("/sms")
    public String sms(){
    
    
        String fromPhone = "15522834580";
        String toPhone = "13820345839";
        String content = "李祥,李祥,今晚王者峡谷 六点 五缺一,收到请回复,over!";
        return smsTemplate.send(fromPhone,toPhone,content);
    }

}

(3) When the configuration file is not configured, the vendor of Alibaba Cloud is used by default.

insert image description here

(4) When the cloud vendor is configured, the configured cloud vendor will be used

insert image description here
insert image description here

Ok, SpringBoot3.x, the custom starter has been completed, and the steps of springboot2.x custom starter will be updated later, because at present, many companies are still using the springboot2.x version.

Guess you like

Origin blog.csdn.net/weixin_47533244/article/details/130703512