【案例实战】SpringBoot3.x自定义封装starter实战

简介: 【案例实战】SpringBoot3.x自定义封装starter实战

1.starter背景简介及作用

(1)什么是starter

starter是SpringBoot中的一个新发明,它有效的下降了项目开发过程的复杂程度,对于简化开发操做有着很是好的效果。

starter的理念:starter会把全部用到的依赖都给包含进来,避免了开发者本身去引入依赖所带来的麻烦。须要注意的是不一样的starter是为了解决不一样的依赖,因此它们内部的实现可能会有很大的差别,例如jpa的starter和Redis的starter可能实现就不同,这是由于starter的本质在于synthesize,这是一层在逻辑层面的抽象,也许这种理念有点相似于Docker,由于它们都是在作一个“包装”的操做,若是你知道Docker是为了解决什么问题的,也许你能够用Docker和starter作一个类比。

(2)自定义starter的背景

  • 大家应该都用过不少Starter,中间件很多,但也存在很多中间件缺少Starter或者不兼容
  • 比如Spring Boot 3.x 版本更新,部分Starter就还没来得及更新,则使用不了
  • 实际企业里面技术组长或架构师也会根据项目需求
  • 封装自己的项目组的Starter,达到更快开发的项目,且可以统一规范,简化配置

(3)自定义Starter封装规范

  • 官方的Starter包规范:spring-boot-starter-xxx
  • 自定义Starter包规范: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)新版Spring Boot3.X和旧版SpringBoot2.7之前自定义Starter区别

  • SpringBoot2.7之前
  • META-INF/spring.factories文件里添加
  • org.springframework.boot.autoconfigure.EnableAutoConfiguration=XXAutoConfiguration
  • 关于springboot2.7之前自定义starter我会用另外一篇文章来展示。这里后续会更新哦!

b4f61602d7124a07bfb2f2ccd310da4a.jpg

SpringBoot2.7推出新的自动配置

  • 在META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
  • 文件里添加配置类名称,每行包含一个配置类全限定名
  • 兼容META-INF/spring.factories方式
  • SpringBoot3.x 移除spring.factories
  • 移除META-INF/spring.factories方式
  • 只支持META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 增加自动配置

2.自定义starter的步骤

 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>3.0.2</version>
</dependency>
  • 创建配置类
  • 创建XXAutoConfiguration类
  • 增加Condition条件注解
  • 配置AutoConfiguration.imports自动配置类

3.自定义starter案例实战

(1)需求背景

  • 现在公司所有的短信发送都集成到消息中心,为了简化各个平台的开发,自定义封装一个sms-starter提供给各个平台使用。
  • 自定义一个发短信的sms-starter,starter对接各个三方的短信平台,阿里云、腾讯云、亚马逊云,开发者可以根据配置进行配置 短信的提供方,默认是 阿里云的提供方。
  • 如果Spring容器没有对应的bean则创建,有的话则不创建。
  • (2)创建SpringBoot3.x项目 sms-spring-boot-starter,添加autoconfigure依赖

e5d2f8fc07ee4935b0e474f08eda1508.jpg

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

(3)创建配置类,通过 @ConfigurationProperties注解可以绑定application.yml配置文件

  • 创建短信运营商的类型枚举类
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)创建SmsService接口,封装三个云厂商的发送短信实现。

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)定义SmsTemplate用于统一提供服务

/**
 * @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)定义SmsAutoConfiguration类

/**
 * @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)创建imports配置文件,把需要自动装载的类配置上。

  • @AutoConfiguration 是spring boot2.7新引入的,自动配置类必须放进下面的文件里才算自动配置类


  • META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

48ff6f443ce64fe994ffa7d7371ce71a.jpg

com.lixiang.config.SmsAutoConfiguration

(8)mvn clean install 打入到本地仓库

cd69dbe6a807468484ba80fe399b89fa.jpg

4.验证自定义starter

(1)新建项目,注意一定要是springboot3.x版本以上的。

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

(2)创建测试代码

@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)当配置文件不进行配置时,默认走的是阿里云的厂商。

bffe578d8ece4a39b02efdd317592c32.jpg

(4)当配置好云厂商时,就会走配置的云厂商


bf589487fa884319ba8df8ae3de09085.jpg

8eba54599dde47bd934e30055b5dfec9.jpg

Ok,SpringBoot3.x,自定义starter已经完成啦,后续会更新springboot2.x自定义starter的步骤,因为目前来看,很多企业还在用springboot2.x的版本。

相关文章
|
2月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
404 3
|
12天前
|
监控 Cloud Native Java
Spring Boot 3.x 微服务架构实战指南
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Spring Boot 3.x与微服务架构,探索云原生、性能优化与高可用系统设计。以代码为笔,在二进制星河中谱写极客诗篇。关注我,共赴技术星辰大海!(238字)
Spring Boot 3.x 微服务架构实战指南
|
25天前
|
消息中间件 Ubuntu Java
SpringBoot整合MQTT实战:基于EMQX实现双向设备通信
本教程指导在Ubuntu上部署EMQX 5.9.0并集成Spring Boot实现MQTT双向通信,涵盖服务器搭建、客户端配置及生产实践,助您快速构建企业级物联网消息系统。
288 1
|
7月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult&lt;T&gt;`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码&quot;0&quot;和消息&quot;操作成功!&quot;,有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
562 0
|
3月前
|
JSON Java 数据格式
Spring Boot返回Json数据及数据封装
在Spring Boot中,接口间及前后端的数据传输通常使用JSON格式。通过@RestController注解,可轻松实现Controller返回JSON数据。该注解是Spring Boot新增的组合注解,结合了@Controller和@ResponseBody的功能,默认将返回值转换为JSON格式。Spring Boot底层默认采用Jackson作为JSON解析框架,并通过spring-boot-starter-json依赖集成了相关库,包括jackson-databind、jackson-datatype-jdk8等常用模块,简化了开发者对依赖的手动管理。
412 3
|
7月前
|
缓存 NoSQL Java
基于SpringBoot的Redis开发实战教程
Redis在Spring Boot中的应用非常广泛,其高性能和灵活性使其成为构建高效分布式系统的理想选择。通过深入理解本文的内容,您可以更好地利用Redis的特性,为应用程序提供高效的缓存和消息处理能力。
566 79
|
5月前
|
监控 Java 调度
SpringBoot中@Scheduled和Quartz的区别是什么?分布式定时任务框架选型实战
本文对比分析了SpringBoot中的`@Scheduled`与Quartz定时任务框架。`@Scheduled`轻量易用,适合单机简单场景,但存在多实例重复执行、无持久化等缺陷;Quartz功能强大,支持分布式调度、任务持久化、动态调整和失败重试,适用于复杂企业级需求。文章通过特性对比、代码示例及常见问题解答,帮助开发者理解两者差异,合理选择方案。记住口诀:单机简单用注解,多节点上Quartz;若是任务要可靠,持久化配置不能少。
523 4
|
6月前
|
缓存 安全 Java
深入解析HTTP请求方法:Spring Boot实战与最佳实践
这篇博客结合了HTTP规范、Spring Boot实现和实际工程经验,通过代码示例、对比表格和架构图等方式,系统性地讲解了不同HTTP方法的应用场景和最佳实践。
572 5
|
8月前
|
Java Spring
SpringBoot 实战 不同参数调用不同实现
本文介绍了如何在实际工作中根据不同的入参调用不同的实现,采用`map+enum`的方式实现优雅且严谨的解决方案。通过Spring Boot框架中的工厂模式或策略模式,避免了使用冗长的`if...else...`语句。文中详细展示了定义接口、实现类、枚举类以及控制器调用的代码示例,确保用户输入的合法性并简化了代码逻辑。
210 1
SpringBoot 实战 不同参数调用不同实现
|
8月前
|
Java Maven 开发者
编写SpringBoot的自定义starter包
通过本文的介绍,我们详细讲解了如何创建一个Spring Boot自定义Starter包,包括自动配置类、配置属性类、`spring.factories`文件的创建和配置。通过自定义Starter,可以有效地复用公共配置和组件,提高开发效率。希望本文能帮助您更好地理解和应用Spring Boot自定义Starter,在实际项目中灵活使用这一强大的功能。
585 17

热门文章

最新文章