如何将Maven构建依赖存储到build目录并生成易读版本清单?
解决建议
1. 定制dependency:list生成简洁清单
在项目的pom.xml中配置maven-dependency-plugin,指定输出格式与路径,过滤冗余信息:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.6.1</version> <executions> <execution> <id>generate-dependency-list</id> <phase>verify</phase> <goals> <goal>list</goal> </goals> <configuration> <!-- 输出到build目录下的dependency-list.txt --> <outputFile>${project.build.directory}/dependency-list.txt</outputFile> <!-- 只保留groupId:artifactId:version核心信息 --> <outputFormat>groupId:artifactId:version</outputFormat> <!-- 排除测试依赖,按需开启 --> <excludeScope>test</excludeScope> <!-- 仅保留直接依赖,不需要传递依赖则开启 --> <includeDirectDependenciesOnly>true</includeDirectDependenciesOnly> </configuration> </execution> </executions> </plugin> </plugins> </build>
执行mvn verify后,build目录会生成每行一个依赖的简洁清单,格式清晰易读。
2. 用dependency:tree生成精简层级清单
如果需要保留依赖层级关系,可通过参数调整输出格式并写入文件:
mvn dependency:tree -DoutputFile=${project.build.directory}/dependency-tree.txt -DoutputFormat=plain -Dincludes=*:*:* -Dverbose=false
该命令会生成仅包含groupId:artifactId:version的层级清单,去掉冗余的scope、类型等信息,适合需要查看依赖关联的场景。
3. 自定义生成灵活格式的清单
若上述方式无法满足需求,可结合maven-antrun-plugin实现完全自定义的输出:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-antrun-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <id>generate-custom-dependency-list</id> <phase>verify</phase> <goals> <goal>run</goal> </goals> <configuration> <tasks> <echo file="${project.build.directory}/custom-deps.txt" append="false"> 依赖清单(生成时间:${maven.build.timestamp}) ====================================== <foreach target="print-dep" param="dep"> <path> <dependencies pathId="project.dependencies"/> </path> </foreach> </echo> <target name="print-dep"> <echo file="${project.build.directory}/custom-deps.txt" append="true"> ${dep.groupId}:${dep.artifactId}:${dep.version} </echo> </target> </tasks> </configuration> </execution> </executions> </plugin> </plugins> </build>
这种方式可自由控制输出格式,比如添加生成时间、自定义表头,适合有特殊格式要求的场景。
补充说明
- 插件版本可根据你使用的Maven版本调整,确保兼容性。
- 若需要包含传递依赖,将
includeDirectDependenciesOnly设为false即可。 - 也可直接通过命令行指定输出,无需修改pom.xml:
mvn dependency:list -DoutputFile=build/dependency-list.txt -DoutputFormat=groupId:artifactId:version
内容的提问来源于stack exchange,提问作者Prkpll
相关产品推荐
相关产品推荐

