在 Spring Boot 生态中,Starter 是一种非常方便的模块化方式,它可以帮助我们快速集成第三方库或自定义功能。本文将带你一步步实现一个自定义的 MyBatis Starter,并将其发布到 Maven 仓库中,供其他项目使用。
1 什么是 MyBatis Starter?
MyBatis 是一个优秀的持久层框架,而 MyBatis Starter 是 Spring Boot 提供的一个官方 Starter,用于快速集成 MyBatis。通过自定义 Starter,我们可以封装一些通用的 MyBatis 配置、插件或工具类,简化项目的配置和开发。
2 实现目标
我们将实现一个自定义的 MyBatis Starter,包含以下功能:
- 自动配置 MyBatis 数据源。
- 自动扫描 Mapper 接口。
3 项目结构
4 实现步骤
在实现自定义 MyBatis Starter 的过程中,我们需要完成以下三个主要步骤:
- 创建 autoconfigure 模块:实现自动配置逻辑。
- 创建 starter 模块:依赖 autoconfigure 模块,并提供默认配置。
- 使用自定义 Starter:在其他 Spring Boot 项目中引入并使用自定义 Starter。
4.1 创建autoconfigure
- 创建maven项目
在 pom.xml 中定义项目依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>3.4.3</version></dependency><!--jdbc--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId><version>3.4.3</version></dependency><!--mybatis--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.14</version></dependency><!--MyBatis与Spring框架集成的桥梁--><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>3.0.3</version></dependency>
- 实现自动配置类
@AutoConfiguration
public class MybatisAutoConfig {@Bean// 自动配置 MyBatis 数据源。public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {// 创建一个SqlSessionFactoryBean对象SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();// 设置数据源sqlSessionFactoryBean.setDataSource(dataSource);// 返回SqlSessionFactoryBean对象return sqlSessionFactoryBean;}@Bean// 自动扫描 Mapper 接口。public MapperScannerConfigurer mapperScannerConfigurer(BeanFactory beanFactory) {// 创建一个MapperScannerConfigurer对象MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();// 获取自动配置的包列表List<String> basePackages = AutoConfigurationPackages.get(beanFactory);// 设置MapperScannerConfigurer的基础包mapperScannerConfigurer.setBasePackage(basePackages.get(0));// 设置MapperScannerConfigurer的注解类mapperScannerConfigurer.setAnnotationClass(Mapper.class);// 返回MapperScannerConfigurer对象return mapperScannerConfigurer;}
}
- 注册自动配置
- 打包:使用以下命令将项目打包并发布到 Maven 仓库:
mvn clean install
4.2 创建starter
- 创建Maven项目
- 定义项目依赖
<dependency><groupId>com.wfs</groupId><artifactId>wmybatis-spring-boot-autoconfigure</artifactId><version>1.0-SNAPSHOT</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><version>3.4.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId><version>3.4.3</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.14</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>3.0.3</version></dependency>
- 打包至maven仓库
4.3 使用自定义 Starter
- 在其他 Spring Boot 项目中引入自定义 Starter(该项目详细描述情请看:Springboot基础篇(2):SpringBoot整合Mybatis):
- 效果图