一、整体项目目录结构
二、搭建步骤
1、创建父工程
- IDEA 工具栏选择菜单 File -> New -> Project...
- 选择Spring Initializr,Initializr默认选择Default,点击Next
- 填写输入框,点击Next
- 这步不需要选择直接点Next
- 点击Finish创建项目
- 删除无用的.mvn目录、src目录、mvnw及mvnw.cmd文件,最终只留.gitignore和pom.xml
2、创建子模块
- 选择项目根目录beta右键呼出菜单,选择New -> Module
- 选择Maven,点击Next
- 填写ArifactId,点击Next
- 修改Module name增加横杠提升可读性,点击Finish
- 同理添加【beta-dao】、【beta-web】子模块,最终得到项目目录结构如下图
3、运行项目
- 在beta-web层创建com.yibao.beta.web包(注意:这是多层目录结构并非单个目录名,com >> yibao >> beta >> web)并添加入口类BetaWebApplication.java
- 在com.yibao.beta.web包中添加controller目录并新建一个controller,添加test方法测试接口是否可以正常访问
- 运行BetaWebApplication类中的main方法启动项目,默认端口为8080,访问http://localhost:8080/demo/test得到如下效果
4、配置模块间的依赖关系
各个子模块的依赖关系:biz层依赖dao层,web层依赖biz层
- 父pom文件中声明所有子模块依赖(dependencyManagement及dependencies的区别自行查阅文档)
其中${beta.version}定义在properties标签中
- 在beta-web层中的pom文件中添加beta-biz依赖
- 在beta-biz层中的pom文件中添加beta-dao依赖
5、web层调用biz层接口测试
- 在beta-biz层创建com.yibao.beta.biz包,添加service目录并在其中创建DemoService接口类
- DemoController通过@Autowired注解注入DemoService,修改DemoController的test方法使之调用DemoService的test方法,最终如下所示
- 再次运行BetaWebApplication类中的main方法启动项目,发现如下报错
***************************
APPLICATION FAILED TO START
***************************
Description:
Field demoService in com.yibao.beta.web.controller.DemoController required a bean of type 'com.yibao.beta.biz.service.DemoService' that could not be found.
Action:
Consider defining a bean of type 'com.yibao.beta.biz.service.DemoService' in your configuration.
原因是找不到DemoService类,此时需要在BetaWebApplication入口类中增加包扫描,设置@SpringBootApplication注解中的scanBasePackages值为com.yibao.beta,最终如下所示
设置完后重新运行main方法,项目正常启动,访问http://localhost:8080/demo/test得到如下效果
6、集成Mybatis
- 父pom文件中声明mybatis-spring-boot-starter及lombok依赖
- 在beta-dao层中的pom文件中添加上述依赖
- 在beta-dao层创建com.yibao.beta.dao包,通过mybatis-genertaor工具生成dao层相关文件(DO、Mapper、xml),存放目录如下
- applicatio.properties文件或application.yml文件添加jdbc及mybatis相应配置项
- DemoService通过@Autowired注解注入UserMapper,修改DemoService的test方法使之调用UserMapper的selectByPrimaryKey方法,最终如下所示
userMapper注入报错是idea工具问题,可尝试着将 @Autowired 注解换成 @Resource
- 再次运行BetaWebApplication类中的main方法启动项目,发现如下报错
APPLICATION FAILED TO START
***************************
Description:
Field userMapper in com.yibao.beta.biz.service.impl.DemoServiceImpl required a bean of type 'com.yibao.beta.dao.mapper.UserMapper' that could not be found.
Action:
Consider defining a bean of type 'com.yibao.beta.dao.mapper.UserMapper' in your configuration.
原因是找不到UserMapper类,此时需要在BetaWebApplication入口类中增加dao层包扫描,添加@MapperScan注解并设置其值为com.yibao.beta.dao.mapper,最终如下所示
设置完后重新运行main方法,项目正常启动,访问http://localhost:8080/demo/test得到如下效果
至此,一个简单的SpringBoot+Mybatis多模块项目已经搭建完毕。
三、未提及的坑
MAVEN打包时报错“程序包xxx不存在”
解决办法:
将ROOT中的spring-boot-maven-plugin更换成org.apache.maven.plugins,如下所示:
OVER
四、项目地址