You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot3下如何避免Swagger接收大响应时崩溃?

解决SpringBoot 3中Swagger处理大响应崩溃的问题

针对测试返回大响应的接口时Swagger持续崩溃、关闭语法高亮仍无效的情况,可尝试以下几种方案:

方案1:让Swagger直接下载大响应而非预览

接口级配置

在返回大响应的接口方法上,通过@ApiResponse注解指定响应的Content-Type为application/octet-stream,Swagger UI会自动触发文件下载,避免将大内容加载到预览窗口:

@GetMapping("/large-response")
@ApiResponse(responseCode = "200", content = @Content(mediaType = "application/octet-stream"))
public ResponseEntity<byte[]> getLargeResponse() {
    // 业务逻辑返回大字节数组
}

全局配置(可选)

如果需要批量处理多个大响应接口,可通过springdoc配置全局修改Swagger UI的响应处理行为,添加到application.yml:

springdoc:
  swagger-ui:
    syntaxHighlight:
      activated: false
    # 强制所有响应以下载形式呈现
    responseContainer: "download"

方案2:增大Swagger UI的响应大小限制

Swagger UI默认对显示的响应大小有上限,超过阈值会导致崩溃,可通过配置提高这个上限:

springdoc:
  swagger-ui:
    syntaxHighlight:
      activated: false
    # 设置最大显示响应大小,单位为字节,示例为10MB
    responseMaxSize: 10485760

方案3:自定义Swagger UI处理逻辑

如果以上方案仍不满足需求,可自定义Swagger UI的初始化脚本,添加大响应自动下载的判断逻辑。在项目的static/swagger-ui/目录下新建swagger-initializer.js(无目录则手动创建),添加代码:

window.onload = function() {
  const ui = SwaggerUIBundle({
    url: "/v3/api-docs",
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  });

  // 拦截响应,超过1MB则触发下载
  const originalExecute = ui.execute;
  ui.execute = function() {
    const result = originalExecute.apply(this, arguments);
    result.then(response => {
      if (response.body && response.body.length > 1048576) {
        const blob = new Blob([response.body]);
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'large-response.bin';
        a.click();
        URL.revokeObjectURL(url);
      }
    });
    return result;
  };

  window.ui = ui;
};

内容的提问来源于stack exchange,提问作者drocky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:58:17