openapi-generator-maven-plugin批量生成文档与父POM配置咨询
解决方案
两个需求都可以实现,无需在子模块编写重复配置,也无需逐个枚举YAML文件名,具体实现方式如下:
1. 父POM统一配置逻辑
所有子模块目录结构完全一致的前提下,直接将插件配置写在父POM的<build><plugins>节点下即可(注意不要放在<pluginManagement>节点中,该节点仅声明配置不实际执行)。
配置中使用${project.basedir}指代当前构建模块的根目录,每个子模块执行构建时会自动替换为自身路径,读取自身目录下的docs文件夹内容,子模块无需额外添加任何插件配置。
2. 批量扫描YAML文件实现
openapi-generator-maven-plugin原生单执行项仅支持指定单个inputSpec文件,不支持通配符扫描,可以搭配GMavenPlus插件在构建初始化阶段自动扫描所有YAML文件,动态为每个文件生成对应的文档生成任务,无需手动逐个配置。
完整父POM配置示例
<?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>your.groupId</groupId> <artifactId>parent</artifactId> <version>your.version</version> <packaging>pom</packaging> <modules> <module>module1</module> <module>module2</module> <module>module3</module> </modules> <build> <plugins> <!-- 扫描docs目录下所有YAML文件,动态生成文档构建任务 --> <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>add-openapi-html-executions</id> <phase>initialize</phase> <goals> <goal>execute</goal> </goals> <configuration> <scripts> <script><![CDATA[ import java.io.File File docsDir = new File(project.basedir, "docs") if (docsDir.exists() && docsDir.isDirectory()) { docsDir.listFiles({ File f -> f.isFile() && (f.name.endsWith(".yaml") || f.name.endsWith(".yml")) } as FileFilter).each { yamlFile -> // 提取无后缀文件名作为输出子目录,避免多文件生成时资源覆盖 String fileName = yamlFile.name.substring(0, yamlFile.name.lastIndexOf(".")) def openapiPlugin = project.build.plugins.find { it.artifactId == "openapi-generator-maven-plugin" } openapiPlugin.executions { execution { id "openapi-html-${fileName}" goals "generate" configuration { inputSpec yamlFile.absolutePath generatorName "html2" output "${project.build.directory}/site/api/${fileName}" } } } } } ]]></script> </scripts> </configuration> </execution> </executions> </plugin> <!-- 统一管理OpenAPI生成插件版本 --> <plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.0.0</version> </plugin> </plugins> </build> </project>
3. 使用说明与注意事项
- 配置完成后在父项目根目录执行
mvn clean generate-sources或正常打包命令即可,所有子模块会自动扫描自身docs目录下的所有YAML文件生成HTML文档 - 每个YAML对应的HTML会输出到
target/site/api/[YAML文件名]/目录下,避免多文件生成时首页、静态资源互相覆盖 - 如果个别子模块不需要执行文档生成,只需在对应子模块的POM中给openapi-generator-maven-plugin添加
<skip>true</skip>配置即可 - 无docs目录的子模块会自动跳过该任务,不会抛出构建错误
内容的提问来源于stack exchange,提问作者Greta
相关产品推荐
相关产品推荐

