如何让swagger-ui/index.html加载手动生成的OAS文档
解决方案
方案一:通过springdoc配置直接指定自定义文档路径
这是最简便的方式,无需修改静态文件,直接在Spring Boot配置文件(application.properties 或 application.yml)中添加配置:
- 若使用properties格式:
springdoc.swagger-ui.url=/swagger.json
- 若使用yml格式:
springdoc: swagger-ui: url: /swagger.json
将你的自定义swagger.json或swagger.yaml文件放到src/main/resources/static目录下,启动项目后访问swagger-ui/index.html,页面会自动加载指定的文档。
方案二:使用swagger-configuration.yaml配置文件
- 文件放置位置:将
swagger-configuration.yaml放在src/main/resources/static或src/main/resources/META-INF/resources目录下,Swagger UI会自动识别该文件。 - 配置语法示例:
如果要直接内嵌文档内容,写法如下:
spec: openapi: 3.0.1 info: title: 自定义API文档 version: 1.0.0 paths: /api/user/{id}: get: summary: 根据ID获取用户信息 responses: '200': description: 查询成功,返回用户数据
如果想指向本地文件路径,也可以用url字段替代spec:
url: /swagger.yaml
方案三:修改Swagger UI的index.html嵌入自定义JSON
- 从springdoc-openapi-ui依赖中复制默认的
index.html,放到src/main/resources/static/swagger-ui目录下(该目录下的文件会覆盖默认页面)。 - 修改页面内的初始化脚本,将自定义JSON作为
spec参数传入:
<script> window.onload = function() { const ui = SwaggerUIBundle({ spec: { "openapi": "3.0.1", "info": { "title": 自定义API文档, "version": "1.0.0" }, "paths": { "/api/user/{id}": { "get": { "summary": 根据ID获取用户信息, "responses": { "200": { "description": 查询成功,返回用户数据 } } } } } }, dom_id: '#swagger-ui', deepLinking: true, presets: [ SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset ], plugins: [ SwaggerUIBundle.plugins.DownloadUrl ], layout: "StandaloneLayout" }); window.ui = ui; }; </script>
保存后启动项目,访问swagger-ui/index.html即可加载嵌入的自定义文档。
内容的提问来源于stack exchange,提问作者Cristian David Moraleda
相关产品推荐
相关产品推荐

