如何编写一个Spring Boot Starter

文章目录

    • 概要
    • 创建一个 Spring Boot Starter 的步骤
      • 创建一个 Maven 项目
      • 打包并发布
    • 在其他项目中使用
    • 总结

概要

写一个 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:


<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.0modelVersion>

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

    <packaging>jarpackaging>

    <groupId>com.hacgroupId>
    <artifactId>hello-service-starterartifactId>
    <version>0.0.1-SNAPSHOTversion>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>
    dependencies>
project>

打包并发布

如何编写一个Spring Boot Starter_第1张图片

mvn clean install

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

在其他项目中使用

一、引入依赖

<dependency>
    <groupId>com.hacgroupId>
    <artifactId>hello-service-starterartifactId>
    <version>0.0.1-SNAPSHOTversion>
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~~❤

你可能感兴趣的:(java,spring,boot,后端,java,maven)