【实战教程】构建可复用的 Spring Boot starter 微服务组件

案例 Demohttps://gitee.com/regexpei/coding-trainee/tree/demo/20240526_starter

介绍

在 Spring Boot 中,starter 启动依赖就像一个"开箱即用"的工具箱,它包含了第三方组件的配置和依赖,让我们无需手动配置和添加这些组件。

通过 starter,我们可以轻松地将通用的代码和配置整合成一个可复用的模块,从而简化项目搭建和代码管理,让开发人员更加专注于业务功能的开发。

那么,我们如何自定义一个 starter 呢?

步骤

  1. 创建 Maven 项目,命名规范为 xxx-spring-boot-starter

  2. 引入依赖

    xml 复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>
    </dependencies>
  3. 定义 XxxProperties 属性配置类,用于绑定 application.yaml 或 application.properties 文件中的配置属性

  4. 编写业务类,根据 starter 的功能需要编写业务逻辑

  5. 配置 XxxAutoConfiguration 自动配置类

    • 使用 @Configuration 标记为配置类
    • 使用 @EnableConfigurationProperties(XxxProperties.class) 绑定配置属性类
  6. 创建 resources/META-INF/spring.factories

    factories 复制代码
    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\  
    xxx.xxx.xxx.XxxAutoConfiguration
  7. 在需要使用的项目中引入 starter

    xml 复制代码
    <dependency>
        <groupId>xxx.xxx</groupId>
        <artifactId>xxx-spring-boot-starter</artifactId>
        <version>1.0.0</version>
    </dependency>
相关推荐
殷紫川19 分钟前
90% Java 开发都踩过坑的 @Resource 与 @Autowired
java
程序员老邢22 分钟前
【产品底稿 12】工程架构最终定型:完整模块拆分、分包规范、层级依赖与开发规约全清单
微服务·架构·springboot·多模块·技术债务
kybs199130 分钟前
springboot租车系统--附源码68701
java·hadoop·spring boot·python·django·asp.net·php
过期动态1 小时前
MySQL中的约束
android·java·数据库·spring boot·mysql
wxin_VXbishe1 小时前
springboot新能源车充电站管理系统小程序-计算机毕业设计源码29213
java·c++·spring boot·python·spring·django·php
程序员陆通1 小时前
月烧 400 刀到不到 20 刀:我是怎么把 OpenClaw 的 Token 账单砍掉 95% 的
java·前端·数据库
代码漫谈2 小时前
一文学习 SpringBoot 的 application.yml 配置,基于 Spring Boot 3.2.x
java·spring boot·spring·配置文件
SamDeepThinking2 小时前
程序员如何接受工作内容毫无意义?
java·后端·程序员
三翼鸟数字化技术团队2 小时前
基于Redis ZSet实现分布式优先级队列的技术实践
java·redis
无所事事O_o2 小时前
加密过程及原理浅析
java·加密