在项目中,使用 springdoc-openapi 替代 Springfox 是一个很好的选择,尤其是考虑到未来的升级稳定性和兼容性。springdoc-openapi 基于 OpenAPI 3 规范,提供了更好的兼容性和易于集成的特性。下面是如何使用 springdoc-openapi 来替代 Springfox 的方案。
1. 引入依赖
在 pom.xml
中添加 springdoc-openapi 的相关依赖:
<dependencies><!-- springdoc-openapi 依赖 --><dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-ui</artifactId><version>2.1.0</version> <!-- 请使用最新版本 --></dependency>
</dependencies>
2. 配置 Spring Boot 项目
在 Spring Boot 项目中,不需要做过多配置,springdoc-openapi 会自动扫描并生成 OpenAPI 规范文档。如果需要自定义,可以在配置类中添加一些配置。
例如,在 application.properties
中配置 Swagger 文档路径:
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
遇到的这个问题:
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:
是 Swagger UI 在访问 /v3/api-docs
的时候,无法自动推断 API 的 base URL,常见于以下场景:
- 应用部署在 API 网关之后(如 Zuul、Nginx、K8s ingress)
- 使用动态 servlet registration(如通过
ServletRegistrationBean
动态注册 DispatcherServlet) - 非标准上下文路径或代理路径
解决方案一:手动指定 url
(推荐)
可以在 Swagger UI 加载页的地址后手动附加 OpenAPI 文档地址,例如:
http://localhost:8080/swagger-ui.html?url=/v3/api-docs
如果部署在代理或网关后,比如路径前缀是 /api
,那就变成:
http://example.com/api/swagger-ui.html?url=/api/v3/api-docs
解决方案二:在配置中指定 server.servlet.context-path
如果使用了上下文路径,确保配置正确,例如:
server.servlet.context-path=/api
springdoc.api-docs.path=/v3/api-docs
springdoc.swagger-ui.path=/swagger-ui.html
那么文档路径将变成:
http://localhost:8080/api/swagger-ui.html?url=/api/v3/api-docs
解决方案三:使用 Nginx / 网关时设置转发头
确保代理(如 Nginx 或 API 网关)设置了正确的头部:
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Prefix /api;
并在 application.properties
中启用 springdoc
对这些头部的支持:
springdoc.use-root-path=true
解决方案四:指定 swagger-ui
的 url
属性
也可以通过 Spring 配置类方式强制指定 Swagger UI 加载哪个 OpenAPI 文档:
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class SwaggerConfig {@Beanpublic GroupedOpenApi publicApi() {return GroupedOpenApi.builder().group("default").pathsToMatch("/**").build();}
}
检查点小结
场景 | 解决办法 |
---|---|
本地访问 | http://localhost:8080/swagger-ui.html?url=/v3/api-docs |
有 context-path | swagger-ui.html?url=/上下文路径/v3/api-docs |
在 Nginx / 网关后 | 设置 X-Forwarded-* 头 + springdoc.use-root-path=true |
使用 Zuul / 网关路由 | 使用路由后的完整路径指定 ?url=/xxx/v3/api-docs |