前言
在企业级的项目开发中,系统庞大时,会使用多模块(module)模式来构建项目,接下来我们就详细讲解多模块(module)模式。
工程结构:
父工程:father
子模块:pojo (实体类)
子模块:dao (用于持久化数据跟数据库交互)
子模块:utils (工具类)
子模块:service (业务逻辑)
子模块:web (页面,数据交互,有启动类的模块)
一、搭建工程
1、创建父工程
1、IDEA工具栏选择菜单File ->New -> Project
2、选择Spring Initializr,Initializr默认Default,点击Next
3、输入组织名称和项目名,点击Next
4、创建的是父工程,不需要选择,直接点Next
5、输入项目保存路径,点击Finish创建项目
6、项目工程结构如下
7、接下来删除无用的.mvn目录、src目录、mvnw及mvnw.cmd文件,最终只留.gitignore和pom.xml
2、创建子模块
1、右键选择项目根目录father,选择New -> Module
2、选择Maven,点击Next
3、填写模块名,添加项目名前缀提升可读性,点击Finish
4、同理添加【father-dao】、【father-utils】、【father-service】、【father-web】子模块。
5、整理后的整个项目结构如下:
以上为项目创建的基本结构过程,接下来建立各自依赖关系
二、依赖关系
依赖关系:
pojo 独立,不依赖
dao 依赖 pojo
service 依赖 dao、pojo
web 依赖 service、dao、pojo
父pom文件中声明所有子模块及继承SpringBoot提供的父工程:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<!-- 模块说明:这里声明多个子模块 -->
<modules>
<module>father-pojo</module>
<module>father-dao</module>
<module>father-utils</module>
<module>father-service</module>
<module>father-web</module>
</modules>
<!-- 继承说明:这里继承SpringBoot提供的父工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<!-- 项目说明:这里作为聚合工程的父工程 -->
<groupId>com.example</groupId>
<artifactId>father</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>father</name>
</project>
pojo的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">
<!-- 继承本项目的父工程 -->
<parent>
<artifactId>father</artifactId>
<groupId>com.example</groupId>