
本文旨在解决spring cloud gateway服务api端点无法通过`springdoc-openapi`(swagger ui或`api-docs`)正常展示的问题。核心解决方案在于正确配置`springdoc`以识别并暴露spring boot actuator的`gateway`端点。通过启用`springdoc.show-actuator`和`management.endpoints.web.exposure.include=gateway`,开发者可以确保gateway路由被`springdoc`发现并集成到api文档中,从而提供完整的服务接口视图。
Spring Cloud Gateway API文档集成与展示
在使用Spring Cloud Gateway作为API网关时,我们通常希望通过springdoc-openapi(或其前身springfox)来自动生成和展示网关所代理的API接口文档。然而,一个常见的问题是,即使配置了springdoc,Gateway自身的路由信息也未能体现在生成的OpenAPI文档(/api-docs)或Swagger UI中,导致paths字段为空。这通常是由于springdoc未能正确识别和暴露Spring Boot Actuator提供的Gateway相关端点所致。
问题分析
当springdoc-openapi在Spring Cloud Gateway应用中运行时,它会尝试扫描并聚合所有可用的API端点。对于标准的Spring Web或Spring WebFlux控制器,这通常是自动完成的。但对于Spring Cloud Gateway定义的路由,其信息是通过Spring Boot Actuator的gateway端点暴露的。如果springdoc没有被明确告知要处理Actuator端点,或者gateway端点本身没有被暴露,那么这些路由信息就无法被捕获。
示例中提供的配置及其响应:
spring:
cloud:
gateway:
routes:
- id: testapi
uri: "localhost:8090/api/test/v1"
predicates:
- Path=/sa
filters:
- AddRequestHeader=secure,true
application:
name: gateway-service
server:
port: 8080
springdoc:
api-docs:
path: /api-docs访问localhost:8080/api-docs时,响应中的paths字段为空,表明Gateway路由并未被springdoc识别。
{
"openapi": "3.0.1",
"info": {
"title": "OpenAPI definition",
"version": "v0"
},
"servers": [
{
"url": "http://localhost:8080",
"description": "Generated server url"
}
],
"paths": {}, // 路径为空
"components": {}
}解决方案
要解决此问题,我们需要在application.yml中添加两个关键配置,以确保springdoc能够发现并处理Gateway的Actuator端点。
启用springdoc对Actuator端点的支持:springdoc.show-actuator=true 这个配置告诉springdoc去扫描并包含Spring Boot Actuator暴露的端点。
暴露gateway Actuator端点:management.endpoints.web.exposure.include=gateway Spring Boot Actuator默认不会暴露所有端点。我们需要明确指定要暴露gateway端点,springdoc才能通过它获取Gateway的路由信息。
完整配置示例
将上述两个配置添加到您的application.yml中,与现有配置合并,如下所示:
spring:
cloud:
gateway:
routes:
- id: testapi
uri: "http://localhost:8090/api/test/v1" # 注意:uri通常需要完整协议,例如http://
predicates:
- Path=/sa
filters:
- AddRequestHeader=secure,true
application:
name: gateway-service
server:
port: 8080
springdoc:
api-docs:
path: /api-docs
# 启用springdoc对Actuator端点的支持
show-actuator: true
management:
endpoints:
web:
exposure:
# 暴露gateway Actuator端点
include: gateway注意事项:
- uri字段在实际应用中通常需要包含协议(如http://或lb://用于负载均衡),否则可能导致路由解析问题。此处已修正为http://localhost:8090/api/test/v1。
- management.endpoints.web.exposure.include可以接受逗号分隔的多个端点名称,例如include: health,info,gateway。如果您想暴露所有端点,可以使用include: '*',但出于安全考虑,这在生产环境中不推荐。
- 确保您的项目中已引入spring-boot-starter-actuator和springdoc-openapi-starter-webflux-ui(如果使用WebFlux)或springdoc-openapi-starter-webmvc-ui(如果使用WebMVC)。
验证
完成上述配置后,重新启动Spring Cloud Gateway服务。然后,您可以:
- 访问localhost:8080/api-docs:检查返回的JSON,paths字段现在应该包含Gateway定义的路由信息,例如/sa。
- 访问localhost:8080/swagger-ui.html:在Swagger UI界面中,您应该能看到Gateway代理的/sa端点及其相关信息。
通过这些步骤,您就可以成功地将Spring Cloud Gateway的路由信息集成到springdoc-openapi生成的API文档中,为开发者提供一个更全面、更易于理解的API视图。










