使用swagger-maven-plugin编译后未生成swagger.json的问题求助
嘿,我猜你切换之后要么性能问题还没解决,要么swagger.json没正常生成?问题大概率出在你保留了swagger-core的旧配置上——这俩工具不能同时“干活”,不然运行时swagger-core还是会偷偷扫描API,性能开销自然还在,甚至可能和插件生成的文档冲突。
我帮你梳理下必须做的几个步骤,把切换彻底搞定:
1. 彻底移除swagger-core的Maven依赖
你之前加的swagger-core相关依赖还在pom.xml里的话,运行时它还是会被加载。赶紧删掉这些:
<!-- 删掉所有swagger-core相关依赖,比如 --> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-jersey2-jaxrs</artifactId> <version>x.x.x</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-core</artifactId> <version>x.x.x</version> </dependency>
如果有swagger-annotations依赖可以单独保留,因为插件需要它来识别接口上的Swagger注解,但核心的swagger-core和Jersey集成包必须删掉。
2. 清理web.xml里的swagger-core配置
你之前肯定在web.xml里加了swagger的servlet或者初始化参数,比如把ApiListingResource加到Jersey的provider里了,这些都要删掉:
<!-- 删掉这类配置 --> <init-param> <param-name>jersey.config.server.provider.classnames</param-name> <param-value>io.swagger.jaxrs.listing.ApiListingResource, io.swagger.jaxrs.listing.SwaggerSerializers</param-value> </init-param>
如果有单独的Swagger Servlet配置,也一并移除。确保运行时不会触发swagger-core的API扫描逻辑。
3. 检查swagger-maven-plugin的配置是否正确
针对Jersey JAX-RS项目,插件配置要注意禁用Spring MVC模式,同时指定正确的API包路径。给你个参考配置:
<plugin> <groupId>io.swagger</groupId> <artifactId>swagger-maven-plugin</artifactId> <version>x.x.x</version> <!-- 建议和swagger-annotations版本一致 --> <executions> <execution> <phase>compile</phase> <!-- 编译时生成文档 --> <goals> <goal>generate</goal> </goals> </execution> </executions> <configuration> <apiSources> <apiSource> <springmvc>false</springmvc> <!-- 关键!Jersey不是Spring MVC,必须设为false --> <locations>com.yourcompany.yourproject.rest</locations> <!-- 你的JAX-RS接口所在包 --> <schemes>http,https</schemes> <host>your-api-domain.com</host> <basePath>/api</basePath> <info> <title>Your API Documentation</title> <version>1.0.0</version> <description>Your API Description</description> </info> <outputPath>${project.build.directory}/swagger.json</outputPath> <!-- 编译时生成的位置 --> <swaggerDirectory>src/main/webapp/swagger</swaggerDirectory> <!-- 可选:同步到web目录供前端访问 --> </apiSource> </apiSources> </configuration> </plugin>
4. 验证生成结果
运行mvn compile,去outputPath指定的目录看看有没有生成swagger.json。如果没生成,检查这几点:
locations里的包路径是否正确,有没有包含所有带Swagger注解(@Api、@ApiOperation等)的接口类- 插件版本和你用的
swagger-annotations版本是否兼容 - 接口类的Swagger注解是否正确,有没有漏加必要的标注
5. 配置Swagger UI(如果需要)
如果之前用了Swagger UI,只需要把UI的静态文件放到src/main/webapp目录,然后修改UI的配置文件(比如index.html),让它加载你编译好的静态swagger.json,比如:
const ui = SwaggerUIBundle({ url: "/your-app-context/swagger/swagger.json", // 对应你设置的swaggerDirectory路径 // 其他配置... })
这样一来,运行时就不会有swagger-core的性能开销了,所有文档都是编译时提前生成好的静态文件。
内容的提问来源于stack exchange,提问作者Rahul Dravid




