Maven 父子模块的 pom.xml 文件编写
今天在写课内的实验作业的时候,三个内容要使用的依赖是一样的,于是想使用父子模块来玩玩。
父模块 pom.xml 书写
- 打包方式
<packaging>pom</packaging>
- 聚合子模块
<!-- 聚合子模块 --> <modules><module>../one</module><module>../two</module> </modules>
完整代码如下:
<?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><groupId>org.example</groupId><artifactId>parent</artifactId><version>1.0-SNAPSHOT</version><packaging>pom</packaging><properties><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target></properties><dependencies><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-common</artifactId><version>3.1.4</version></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-mapreduce-client-core</artifactId><version>3.1.4</version></dependency></dependencies><!-- 聚合子模块 --><modules><module>../one</module><module>../two</module></modules></project>
子模块 pom.xml 文件书写
- 父模块信息填写
<parent><groupId>org.example</groupId><artifactId>parent</artifactId><version>1.0-SNAPSHOT</version><relativePath>../parent/pom.xml</relativePath> </parent>
- 自已的信息填写
<artifactId>one</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version>
如何多个模块
先创建项目,再把项目引入 moudle 里
构建模块
在父模块的根目录下执行以下命令来构建所有模块:
mvn clean install
这将会构建父模块以及所有在 <modules>
中定义的子模块
打包依赖的库,自动检测主类
因为通过 maven 依赖管理的父依赖是不会打包进子模块的,可以利用插件打包进去。
如果不是 springboot 项目,还得指明主函数
如果是 springboot 项目,直接
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><executions><execution><goals><goal>repackage</goal><!--可以把依赖的包都打包到生成的Jar包中 --></goals></execution></executions></plugin></plugins></build>
如果是非 springboot 项目,在 pom.xml 文件里
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-shade-plugin</artifactId><version>3.2.4</version><executions><execution><phase>package</phase><goals><goal>shade</goal></goals><configuration><transformers><transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"><mainClass>WordCountDriver.java</mainClass><!-- 主类的位置,例如上图文件,主类配置应为: --><!-- <mainClass>top.nihilwater.App</mainClass> --></transformer></transformers></configuration></execution></executions></plugin></plugins></build>
或者
打开 project struct