【Starter 】Spring Boot 3.x 自定义封装Starter 实战

2024-09-05 13:04

本文主要是介绍【Starter 】Spring Boot 3.x 自定义封装Starter 实战,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【Starter 】Spring Boot 3.x 自定义封装Starter 实战

Starter 背景简介及作用

什么是 Starter

Starter 是 Spring Boot 中的一项创新发明,它的主要作用是降低项目开发中的复杂性,从而简化开发操作。通过使用 Starter,开发人员可以轻松地引入常用的库和配置,避免了繁琐的手动设置。

Starter 的理念:Starter 会将项目中所需的所有依赖一起打包,开发者不需要手动逐个引入依赖。这种设计减少了手动管理依赖的麻烦,确保了所需依赖版本的一致性。不同的 Starter 是为了解决不同的场景需求,比如 JPA 和 Redis 各有对应的 Starter,这种差异是由于 Starter 本质上是对逻辑层的封装和抽象。类似于 Docker 的概念,Starter 通过封装帮助开发者快速解决复杂问题。

例如,spring-boot-starter-data-jpa 就会自动配置与 JPA 相关的依赖和配置,而开发者只需将其引入即可使用 JPA 功能,而不必手动处理配置。

自定义 Starter 的背景

虽然在开发中我们经常使用官方的 Starter,例如数据库、缓存、消息队列等中间件的 Starter,但在实际开发中仍然会遇到一些情况:

  • 某些中间件没有官方 Starter 支持,开发者需要自行引入相关依赖并手动配置。
  • Spring Boot 版本更新后,部分官方 Starter 未能及时更新,导致无法兼容新版本。

在企业中,技术负责人或架构师通常会根据项目的实际需求,封装属于自己团队的自定义 Starter。这种自定义 Starter 通过统一的规范与配置,极大地简化了项目的开发流程,提升了开发效率。例如,封装数据库访问、认证授权、消息服务等,所有项目组成员都可以统一使用,提高了代码的规范性和一致性。

自定义 Starter 封装规范

  • 官方的 Starter 包命名规范为:spring-boot-starter-xxx,如 spring-boot-starter-webspring-boot-starter-jdbc

  • 自定义 Starter 的命名规范建议为:xxx-spring-boot-starter,如 mycompany-spring-boot-starter-email,这种命名方式便于团队识别自定义的 Starter,同时遵循 Spring 的命名风格。

自定义 Starter 通常包含以下内容:

  1. 自动配置类@Configuration):定义好依赖的自动配置逻辑。
  2. 配置属性类@ConfigurationProperties):支持使用外部化配置参数来简化使用。
  3. 必要的依赖管理:将常用的第三方库一并引入,避免手动添加依赖。

通过自定义 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

新版Spring Boot3.X和旧版Spring Boot2.7之前自定义Starter区别

SpringBoot 2.7 之前

META-INF/spring.factories 文件里添加org.springframework.boot.autoconfigure.EnableAutoConfiguration=XXAutoConfiguration

Spring Boot2.7 推出新的自动配置

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

文件里添加配置类名称,每行包含一个配置类全限定名;

兼容META-INF/spring.factories方式;

Spring Boot3.x 移除spring.factories;

移除META-INF/spring.factories方式;

只支持META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 增加自动配置。

自定义starter的步骤

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

自定义 Starter 案例实战

需求背景

目前公司所有的短信发送功能都已集成到消息中心。为了简化各个平台的开发流程,计划自定义封装一个 codingce-sms-spring-boot-starter,供各个平台统一使用。

这个 codingce-sms-spring-boot-starter 需要能够对接多家第三方短信平台,包括阿里云、腾讯云、亚马逊云等。开发者可以通过配置灵活选择短信服务提供商,默认情况下使用腾讯云作为短信服务商。如果 Spring 容器中不存在相应的 bean,则自动创建;如果已经存在,则不再创建。

创建SpringBoot3.x项目

codingce-sms-spring-boot-starter,添加autoconfigure依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId><version>3.0.2</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>

SmsAutoConfiguration

package cn.com.codingce.sms.config;import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;/*** @author Will*/
@AutoConfiguration
@ConditionalOnClass({SmsTemplate.class})
@EnableConfigurationProperties(value = SmsProperties.class)
public class SmsAutoConfiguration {@Bean@ConditionalOnMissingBeanpublic SmsTemplate smsTemplate() {return new SmsTemplate();}}

SmsProperties

package cn.com.codingce.sms.config;import cn.com.codingce.sms.constant.SmsTypeEnum;
import org.springframework.boot.context.properties.ConfigurationProperties;/*** @author Will*/
@ConfigurationProperties(prefix = "sms.server.achieve")
public class SmsProperties {/*** 发送短信类型*/private String type;public String getType() {if (type == null || "".equals(type)) {type = SmsTypeEnum.TX_CLOUD.name();}return type;}public void setType(String type) {this.type = type;}}

SmsTemplate

package cn.com.codingce.sms.config;import cn.com.codingce.sms.factory.SmsHandleFactory;
import cn.com.codingce.sms.service.SmsService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;/*** @author Will*/
public class SmsTemplate {@Autowiredprivate SmsProperties smsProperties;@ResourceSmsHandleFactory smsHandleFactory;public String send(String fromPhone, String toPhone, String content) {//获取云厂商的业务实现类String type = smsProperties.getType();SmsService smsService = smsHandleFactory.createSmsService(type);return smsService.send(fromPhone, toPhone, content);}}

SmsTypeEnum

package cn.com.codingce.sms.constant;/*** @author Will*/
public enum SmsTypeEnum {//阿里云ALI_CLOUD("ali"),//腾讯云TX_CLOUD("tx"),//亚马逊云YMX_CLOUD("ymx");private String type;SmsTypeEnum(String ymx) {}}

SmsHandleFactory

package cn.com.codingce.sms.factory;import cn.com.codingce.sms.service.SmsService;
import org.springframework.stereotype.Component;import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;/*** @author Will*/
@Component
public class SmsHandleFactory {public Map<String, SmsService> handlerMap = new ConcurrentHashMap<>();/*** 创建处理类对象** @param code code* @return ISmsService*/public SmsService createSmsService(String code) {return handlerMap.get(code);}}

SmsService

package cn.com.codingce.sms.service;/*** @author Will*/
public interface SmsService {/*** 发送短信** @param fromPhone fromPhone* @param toPhone   toPhone* @param content   content* @return String*/String send(String fromPhone, String toPhone, String content);}

AliCloudSmsServiceImpl

package cn.com.codingce.sms.service.impl;import cn.com.codingce.sms.factory.SmsHandleFactory;
import cn.com.codingce.sms.service.SmsService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;/*** 阿里云SMS实现** @author Will*/
@Service("ali")
public class AliCloudSmsServiceImpl implements SmsService {@ResourceSmsHandleFactory smsHandleFactory;static final String ALI = "ali";@PostConstructpublic void init() {smsHandleFactory.handlerMap.put(ALI, this);}@Overridepublic 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";}
}

TxCloudSmsServiceImpl

package cn.com.codingce.sms.service.impl;import cn.com.codingce.sms.factory.SmsHandleFactory;
import cn.com.codingce.sms.service.SmsService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;/*** 腾讯云SMS实现** @author ma*/
@Service("tx")
public class TxCloudSmsServiceImpl implements SmsService {@ResourceSmsHandleFactory smsHandleFactory;static final String ALI = "tx";@PostConstructpublic void init() {smsHandleFactory.handlerMap.put(ALI, this);}@Overridepublic 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";}}

YmxCloudSmsServiceImpl

package cn.com.codingce.sms.service.impl;import cn.com.codingce.sms.factory.SmsHandleFactory;
import cn.com.codingce.sms.service.SmsService;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;/*** 亚马逊云SMS实现** @author Will*/
@Service("ymx")
public class YmxCloudSmsServiceImpl implements SmsService {@ResourceSmsHandleFactory smsHandleFactory;static final String ALI = "ymx";@PostConstructpublic void init() {smsHandleFactory.handlerMap.put(ALI, this);}@Overridepublic 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";}}

mvn clean install 打入到本地仓库

使用方

新建项目

注意一定要是spring boot3.x版本以上的。

<dependency><groupId>cn.com.codingce</groupId><artifactId>codingce-sms-spring-boot-starter</artifactId><version>0.0.1-SNAPSHOT</version>
</dependency>

创建测试代码

package com.example.usersdkdemo.controller;import cn.com.codingce.sms.config.SmsTemplate;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author Will*/
@RestController
@RequestMapping("/codingce")
public class SmsController {@Resourceprivate SmsTemplate smsTemplate;@RequestMapping("/sms")public String sms() {String fromPhone = "19922579993";String toPhone = "17694917213";String content = "志国,志国,今晚英雄联盟 十点 五缺一,收到请回复,over!";return smsTemplate.send(fromPhone, toPhone, content);}}

当配置文件不进行配置时,默认走的是腾讯云的厂商

http://localhost:8080/codingce/sms

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

http://localhost:8080/codingce/sms
sms:server:achieve:type: ali

这篇关于【Starter 】Spring Boot 3.x 自定义封装Starter 实战的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1139037

相关文章

Java中对象的创建和销毁过程详析

《Java中对象的创建和销毁过程详析》:本文主要介绍Java中对象的创建和销毁过程,对象的创建过程包括类加载检查、内存分配、初始化零值内存、设置对象头和执行init方法,对象的销毁过程由垃圾回收机... 目录前言对象的创建过程1. 类加载检查2China编程. 分配内存3. 初始化零值4. 设置对象头5. 执行

SpringBoot整合easy-es的详细过程

《SpringBoot整合easy-es的详细过程》本文介绍了EasyES,一个基于Elasticsearch的ORM框架,旨在简化开发流程并提高效率,EasyES支持SpringBoot框架,并提供... 目录一、easy-es简介二、实现基于Spring Boot框架的应用程序代码1.添加相关依赖2.添

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程

《SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程》本文详细介绍了如何在虚拟机和宝塔面板中安装RabbitMQ,并使用Java代码实现消息的发送和接收,通过异步通讯,可以优化... 目录一、RabbitMQ安装二、启动RabbitMQ三、javascript编写Java代码1、引入

spring-boot-starter-thymeleaf加载外部html文件方式

《spring-boot-starter-thymeleaf加载外部html文件方式》本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在SpringBoo... 目录1.Thymeleaf介绍2.springboot使用thymeleaf2.1.引入spring

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在