【实战教程】构建可复用的 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>
相关推荐
鱼跃鹰飞1 天前
设计模式系列:工厂模式
java·设计模式·系统架构
a努力。1 天前
国家电网Java面试被问:混沌工程在分布式系统中的应用
java·开发语言·数据库·git·mysql·面试·职场和发展
Yvonne爱编码1 天前
Java 四大内部类全解析:从设计本质到实战应用
java·开发语言·python
J2虾虾1 天前
SpringBoot和mybatis Plus不兼容报错的问题
java·spring boot·mybatis
毕设源码-郭学长1 天前
【开题答辩全过程】以 基于springboot 的豪华婚车租赁系统的设计与实现为例,包含答辩的问题和答案
java·spring boot·后端
Tao____1 天前
通用性物联网平台
java·物联网·mqtt·低代码·开源
曹轲恒1 天前
SpringBoot整合SpringMVC(上)
java·spring boot·spring
JH30731 天前
Java Spring中@AllArgsConstructor注解引发的依赖注入异常解决
java·开发语言·spring
码农水水1 天前
米哈游Java面试被问:机器学习模型的在线服务和A/B测试
java·开发语言·数据库·spring boot·后端·机器学习·word
2601_949575861 天前
Flutter for OpenHarmony二手物品置换App实战 - 表单验证实现
android·java·flutter