如何手写一个springboot starter?

本文主要分享了如何手写一个spring starter,把你的代码作为jar包进行开源。
命名规则(不要使用spring-boot开头,以避免将来spring-boot官方使用你的starter而重名)
官方命名格式为:spring-boot-starter-xxx
非官方命名格式为:xxx-spring-boot-starter
项目demo:gitee: https://gitee.com/jq_di/file-storage

一、需要开源的原始项目(file-storage-core)

比如你写了一个封装了文件存储的框架,支持本地磁盘、阿里云OSS、MinIO、亚马逊AWS、百度BOS、华为云OBS、京东云OOS、腾讯云COS、网易NOS等。 该项目没有依赖springboot
你希望把这个框架开源出去,让有需要的同行能够在springboot项目中快速使用起来,最好的办法就是你再提供一个springboot starter项目。

二、增加springboot starter项目(file-storage-spring-boot-starter)

1.pom.xml添加自动配置的依赖,scope需要设置为provided,因为version不一定与项目X(依赖starter的项目)一致,所以scope=provided是让项目X决定自动配置依赖的version
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.0.5.RELEASE</version>
    <scope>provided</scope>
</dependency>
2.pom.xml添加file-storage-core的依赖,这里不需要设置scope,这样项目X依赖file-storage-spring-boot-starter之后就会自动把file-storage-core也加入依赖
<dependency>
    <groupId>com.jqdi</groupId>
    <artifactId>file-storage-core</artifactId>
    <version>1.0.0</version>
</dependency>
3.添加FileStorageAutoConfiguration,用于创建spring的Bean
4.在src/main/resources下添加/META-INF/spring.factories,用于完成自动配置(这里是使用了springboot的spi机制,具体可了解一下springboot的自动配置)
疑惑点?
问题1:FileStorageAutoConfiguration上不加@Configuration行不行?
答:行
FileStorageAutoConfiguration的bean是由EnableAutoConfiguration @Import来完成的,并不是通过bean扫描。但是比较奇怪的是业界提供的开源jar,比如RedisAutoConfiguration、RabbitAutoConfiguration、MybatisAutoConfiguration都有保留这个@Configuration注解。
问题2:不要spring.factories这个配置文件行不行?
答:行,但是一般不建议
1)@SpringBootApplication项目会扫描所在根目录和子目录,一般情况下 项目X的package与开源jar包的package都是不一样的,假如是相同的,可跟据1中的 @Configuration直接扫描到 FileStorageAutoConfiguration。
2) 或者在启动类上添加@Import(FileStorageAutoConfiguration.class),该原理与spring.factories方式是一样的。

三、增加项目X的demo(file-storage-springboot-demo)

1.pom.xml添加file-storage-spring-boot-starter的依赖
<dependency>
    <groupId>com.jqdi</groupId>
    <artifactId>file-storage-spring-boot-starter</artifactId>
    <version>1.0.0</version>
</dependency>
2.以@Autowired的方式来使用文件存储的功能
怎么样?如果你觉得有用的话,还不快快收藏起来!!!
附:涉及的代码目录

猜你喜欢

转载自blog.csdn.net/w13528476101/article/details/128997024