Swagger Codegen Maven插件生成路径问题:如何输出到src/main?
问题描述
我无法将Swagger Codegen生成的models、controllers和services文件输出到src/main目录,执行mvn clean install命令后,文件仅生成在target/generate-sources目录下。我已经尝试过使用JSON和YAML格式的配置文件,请问该如何修改配置让文件生成到src/main目录?
解决方案
针对你的pom.xml中swagger-codegen-maven-plugin的配置,做以下关键调整:
1. 启用插件的代码生成目标
原配置中<goals>代码块被注释,导致插件无法主动触发代码生成,需要取消注释:
<goals> <goal>generate</goal> </goals>
2. 修改输出目录与源码路径
当前配置的输出目录指向target,需要调整为项目根目录,并指定源码生成到src/main/java下:
- 将
<output>的值改为${project.basedir} - 在
<configOptions>中把<sourceFolder>修改为src/main/java
调整后的完整插件配置如下:
<plugin> <groupId>io.swagger.codegen.v3</groupId> <artifactId>swagger-codegen-maven-plugin</artifactId> <version>3.0.33</version> <dependencies> <dependency> <groupId>com.github.jknack</groupId> <artifactId>handlebars</artifactId> <version>4.3.0</version> </dependency> </dependencies> <executions> <execution> <id>request-service</id> <goals> <goal>generate</goal> </goals> <configuration> <inputSpec>${reqjson.file}</inputSpec> <artifactId>contract-service</artifactId> <!-- 修改输出目录为项目根目录 --> <output>${project.basedir}</output> <language>spring</language> <generateApis>true</generateApis> <generateModels>true</generateModels> <modelPackage>com.freetrainingzone.identityverification.model</modelPackage> <apiPackage>com.freetrainingzone.identityverification.controller.api</apiPackage> <generateSupportingFiles>false</generateSupportingFiles> <configOptions> <interfaceOnly>false</interfaceOnly> <library>spring-boot</library> <singleContentTypes>true</singleContentTypes> <!-- 指定源码生成到src/main/java目录 --> <sourceFolder>src/main/java</sourceFolder> <dateLibrary>java17</dateLibrary> </configOptions> </configuration> </execution> </executions> </plugin>
3. 可选:更安全的替代方案(避免覆盖自定义代码)
如果后续需要对生成的文件做自定义修改,直接生成到src/main/java会存在被重新生成的代码覆盖的风险。更推荐的做法是保持生成到target目录,然后通过build-helper-maven-plugin将生成的源码添加为maven编译源目录:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>${project.basedir}/target/generated-sources/swagger/src/main/java</source> </sources> </configuration> </execution> </executions> </plugin>
这种方式既保留了自动生成的代码,又不会覆盖你的自定义修改,同时maven会自动将生成的源码纳入编译流程。
内容的提问来源于stack exchange,提问作者codeNEWBYE
相关产品推荐
相关产品推荐

