概述
本文将介绍如何使用maven构建基于springboot的多模块工程。
Maven的多模块项目
多模块项目是通过管理一组子模块的父POM构建而成的。一般情况下父POM位于项目根目录下。
使用多模块的好处
Maven Pom 是,最明显的好处是减少重复以及共享配置,通过配置可指定所需的模块打包,而不是全部打包。
父POM
Maven支持继承,即每个pom.xml文件都具有隐式父POM,它称为Super POM,可以位于Maven二进制文件中。这两个文件由Maven合并并形成有效POM。
因此,我们可以创建自己的pom.xml文件,该文件将用作父项目。然后,我们可以在其中包含所有具有依赖性的配置,并将其设置为子模块的父模块,以便它们从其继承。
除了继承,Maven还提供了聚合的概念。利用此功能的父POM称为聚合POM 。基本上,这种POM 在其pom.xml文件中显式声明其模块。
子模块
子模块或子项目是从父POM继承的常规Maven项目。众所周知,继承使我们可以与子模块共享配置和依赖项。但是,如果我们想一次性生成或发布项目,则必须在父POM中显式声明子模块。最终,我们的父POM将是父POM,也将是聚合POM。
创建多模块工程
环境
IDEA
MAVEN
JDK8
1.创建父POM
- 选择Spring Initializr 。
- 填写项目信息,注意Type 选择Maven POM。后面一直next即可,本次选择的springboot是2.3.0版本。
- 整理POM文件,增加pom,其他暂时不处理。
2.创建子模块
比如根据工程分层分模块。分成common/dao/biz/web 4个子模块。
以其中common模块创建为例,其他模块创建操作相同。
- 在父工程上右键New-Module
- 直接next,注意不要选模板。
* finish。
创建完如下,其他子模块创建与common创建一样操作。
3.打包
父项目由于是pom类型,因此会被排除,并且构建会为所有其他模块生成三个单独的 .jar文件。
- 几个子模块的依赖关系web>biz>dao>common。
- 建立springboot 启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HenApplication {
public static void main(String[] args) {
SpringApplication.run(HenApplication.class,args);
}
}
- web POM中指定打包类型,并依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
...
<!-- 设置打包插件 指定程序入口-->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.chan.hen.HenApplication</mainClass>
</configuration>
</plugin>
</plugins>
</build>
- 建立一个测试controller。
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("test")
public class TestController {
@RequestMapping("/helloWorld")
public String test(String xx){
return xx+":helloWorld!";
}
}
- maven 执行 clean package 命令,打出来的jar包执行。
访问 localhost:8080/test/helloWorld/?xx=hen
成功!
代码地址
https://github.com/flashyunchen/hen.git