Spring Boot多模块项目搭建介绍
本文主要介绍如何使用IDEA搭建多模块的Spring Boot项目,项目使用Spring Boot + MyBatis的技术架构。
一、搭建父模块
- 使用IDEA新建一个Project:
- 选择Spring Initializr,点击【Next】:
- 填写项目的GroupId、ArtifactId等项目信息,因为是示例代码,所以这些项目信息都填写为默认的信息,填写完这些信息之后点击【Next】:
- 在下一页直接点击【Next】:
- 最后填写项目名称,在这里我使用的项目名称为demo,填写完项目名称之后点击【Finish】:
- 自动生成的项目结构如下所示:
- 作为父模块,应该删除不需要的文件夹、文件,在这里,我删除了.mvn文件夹、src文件夹、mvnw、mvnw.cmd,最后保留的项目结构如下:
到这里,父模块的搭建就完成了,下面介绍web子模块的搭建过程。
二、搭建web子模块
web模块作为系统的前端,是整个系统的前台入口,搭建web模块的步骤如下:
- 选中父模块demo,右键,选择New->Moudle…:
- Moudle类型选择Maven,选中Create from archetype,再选择maven-archetype-quickstart,点击【Next】:
- 填写子模块的ArtifactId为demo-web,点击【Next】:
- 下一项直接点击【Next】,到最后修改Moudle name为demo-web,点击【Finish】:
到这里,一个简单的web子模块就建好了,暂时先不调整子模块的Maven依赖,后续会详细介绍。
三、搭建biz子模块和common子模块
biz模块作为系统的业务模块,主要包含系统的业务处理、数据库操作等,属于系统的后台,web模块的功能需要依赖biz模块。
common子模块属于公共模块,它主要包含了一些系统前台、后台都需要使用的信息,例如:常量、异常的定义等,web模块和biz模块都需要依赖于common模块。
biz子模块和common子模块的搭建过程和web子模块类似,这里就不详细介绍了,具体步骤可以参照上面web子模块的搭建步骤,最后所有模块都搭建完成后整个的结构如下:
四、修改模块的依赖
- 先修改父模块的pom.xml,父模块负责管理子模块的依赖,因此需要添加dependencyManagement元素,通过该元素能够确保子模块依赖的jar包版本统一。本项目使用到了Spring Boot、MyBatis,测试用到了JUnit,可以先在父模块中添加这些jar包的依赖:
<properties>
<java.version>1.8</java.version>
<spring.boot.version>2.1.9.RELEASE</spring.boot.version>
<junit.version>4.11</junit.version>
<mybatis.spring.boot.version>2.1.0</mybatis.spring.boot.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.spring.boot.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
- 接着可以添加web子模块的依赖了,web子模块是系统的入口,系统启动之后访问的就是 web子模块,所以Spring Boot的启动程序应该定义在web子模块中,另外因为web子模块依赖于biz子模块和common子模块,因此也需要引入相应模块作为依赖,这样web子模块最后生成的pom.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<groupId>com.example</groupId>
<artifactId>demo-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo-web</name>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>demo-biz</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.example</groupId>
<artifactId>demo-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId