求用Maven自动生成Java项目PlantUML类图的最新教程
Maven 生成 PlantUML 全量类图最新实操方案
以下方案均适配2024年最新技术栈,支持JDK 8~21全版本,无需依赖过时插件。
方案1:一键生成全量类图(适配绝大多数场景)
使用当前持续维护的plantuml-generator-maven-plugin,无需额外编码即可完成全类扫描、关系识别、puml文件生成全流程。
- 在项目
pom.xml的<build><plugins>节点中添加插件配置:
<plugin> <groupId>com.github.javadev</groupId> <artifactId>plantuml-generator-maven-plugin</artifactId> <version>1.28</version> <!-- 2024年最新稳定版 --> <executions> <execution> <phase>process-classes</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <!-- 替换为你项目的根包路径,支持多包用逗号分隔 --> <scanPackages>com.yourproject.root</scanPackages> <!-- 生成puml文件的输出目录 --> <outputDirectory>${project.build.directory}/plantuml</outputDirectory> <!-- 类图展示维度配置,按需开启/关闭 --> <showFields>true</showFields> <showMethods>true</showMethods> <showInheritance>true</showInheritance> <showImplementations>true</showImplementations> <showDependencies>true</showDependencies> <!-- 可选:排除不需要扫描的包/类,多个用逗号分隔 --> <excludePackages>com.yourproject.root.util,com.yourproject.root.config</excludePackages> </configuration> </plugin>
- 执行Maven命令触发生成:
mvn process-classes - 生成的
.puml源文件可直接用PlantUML编辑器打开渲染,也可配合后续的官方渲染插件直接生成图片文件。
方案2:自定义类过滤+渲染(适配大项目按需生成)
如果项目类数量过千,全量生成的类图可读性差,可以用这个方案自定义筛选生成范围:
- 自行编写轻量类扫描代码,过滤出需要展示的类、拼接成PlantUML语法文本,存为
.puml源文件 - 引入官方同步更新的PlantUML Maven插件直接渲染为图片,插件配置如下:
<plugin> <groupId>io.github.plantuml</groupId> <artifactId>plantuml-maven-plugin</artifactId> <version>1.2024.3</version> <!-- 同步PlantUML官方2024年最新版本 --> <executions> <execution> <phase>process-resources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <!-- puml源文件存放路径 --> <sourceDirectory>${project.basedir}/src/main/resources/plantuml</sourceDirectory> <!-- 渲染后的图片输出路径 --> <outputDirectory>${project.build.directory}/plantuml-images</outputDirectory> <!-- 输出格式支持png、svg、pdf等 --> <format>svg</format> </configuration> </plugin>
版本适配说明
如果你使用JDK 16及以上版本,需要在插件的<configuration>节点中添加JVM参数规避反射权限报错:
<jvmArgs> <jvmArg>--add-opens=java.base/java.lang=ALL-UNNAMED</jvmArg> <jvmArg>--add-opens=java.base/java.lang.reflect=ALL-UNNAMED</jvmArg> </jvmArgs>
如果是多模块Maven项目,将插件配置放在根pom的<pluginManagement>节点下,子模块按需引入即可。
内容的提问来源于stack exchange,提问作者Flimtix
相关产品推荐
相关产品推荐

