使用:自定义starter过程
原理:starter原理
springboot starter
starter 是 SpringBoot 中一种非常重要的机制,它可以繁杂的配置统一集成到 starter 中,我们只需要通过 maven 将 starter 依赖引入到项目中,SpringBoot 就能自动扫描并加载相应的默认配置。
使用规范
- 命名规范:
a. springboot官方:spring-boot-starter-xxx。如:spring-boot-starter-web
b. 第三方自定义:xxx-spring-boot-starter。如:mybatis-spring-boot-starter - 模块规范(官方建议,非强制)
a. 自定义 starter 时,创建两个 Module :autoConfigure Module 和 starter Module。其中 starter Module 依赖于 autoConfigure Module
原理:Spring Factories 机制
Spring Factories 机制是 Spring Boot 中的一种服务发现机制,这种机制与 Java SPI 机制十分相似。Spring Boot 会自动扫描所有 Jar 包类路径下 META-INF/spring.factories 文件,并读取其中的内容,进行实例化,这种机制也是 Spring Boot Starter 的基础
自定义starter步骤
- 创建工程
- 添加 POM 依赖
- 定义 propertie 类
- 定义 Service 类
- 定义配置类
- 创建 spring.factories文件
- 构建 starter
项目demo
github仓库地址:springboot-learn
- SpringBootStarterDemo 模块:自定义Starter
- HelloWorld 模块:引入自定义Starter,功能测试