如何编写一个Spring Boot Starter

发布于:2025-03-23 ⋅ 阅读:(17) ⋅ 点赞:(0)

概要

写一个 Spring Boot Starter 其实就是封装一部分功能,方便其他项目引入和使用。Starter 是 Spring Boot 提供的一种机制,目的是为了简化配置模块化开发。一般来说,Spring Boot Starter 会封装一个特定的功能模块,并自动配置一些常用的组件。通过写一个 Starter,用户只需要简单地引入一个依赖,就可以使用该功能。

创建一个 Spring Boot Starter 的步骤

创建一个 Maven 项目

my-spring-boot-starter
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── hac
│   │   │           ├── config
│   │   │           │   └── HelloServiceAutoConfiguration.java
│   │   │           └── service
│   │   │               └── HelloService.java
│   │   └── resources
│   │       └── META-INF
│   │           └── spring.factories
│   └── test
└── pom.xml

代码:

public class HelloService {
    public String sayHello() {
        return "Hello, World!";
    }
}

@Configuration
@ConditionalOnClass(HelloService.class)
public class HelloServiceAutoConfiguration {

    @Bean
    public HelloService helloService() {
        return new HelloService();
    }
}

src/main/resources/META-INF/spring.factories:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.hac.config.HelloServiceAutoConfiguration

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.18</version>
    </parent>

    <packaging>jar</packaging>

    <groupId>com.hac</groupId>
    <artifactId>hello-service-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
</project>

打包并发布

在这里插入图片描述

mvn clean install

说明:mvn install 是 Maven 中用于编译、测试、打包并将构件安装到本地仓库,便于项目管理和依赖共享。

在其他项目中使用

一、引入依赖

<dependency>
    <groupId>com.hac</groupId>
    <artifactId>hello-service-starter</artifactId>
    <version>0.0.1-SNAPSHOT</version>
</dependency>

二、测试

@Controller
public class CartoonController {
    @Resource
    public HelloService helloService;

    @PostConstruct
    public void init() {
        System.out.println(helloService.sayHello()); // 能中共南昌打印出来
    }
}

总结

这只是一个比较简单的示例。根据具体场景实现丰富的 starter 。

注意:

  1. 命名规范:Starter 通常命名为 xxx-spring-boot-starter,自动配置类为 xxxAutoConfiguration。

  2. 版本兼容性:确保与目标项目的 Spring Boot 版本一致。

  3. 发布:考虑将 Starter 发布到 Maven Central 等。【deploy发布到远程仓库(maven私服)】


❤觉得有用的可以留个关注ya~~❤