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

Spring Boot如何针对特定接口禁用Swagger UI的Try it out按钮

Springfox 2.9.2 单接口禁用Swagger UI「Try it out」按钮实现方案

Springfox 原生未提供单接口维度控制「Try it out」按钮的配置项,全局调用supportedSubmitMethods()传入空数组的方案会作用于所有接口,要实现单接口精准禁用,可参考以下两种落地方式:

方案一:自定义标记注解 + 扩展Springfox插件 + 轻量前端逻辑(推荐,侵入性低)

该方案可以精确到任意单个接口,不影响其他接口的正常调试功能

  • 第一步:定义自定义注解用于标记需要禁用按钮的接口
import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DisableTryItOut {
}
  • 第二步:实现Springfox的OperationBuilderPlugin扩展点,给标记了注解的接口添加自定义扩展字段
import org.springframework.stereotype.Component;
import springfox.documentation.service.StringVendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.swagger.common.SwaggerPluginSupport;
import java.util.Collections;

@Component
public class DisableTryItOutOperationPlugin implements OperationBuilderPlugin {
    @Override
    public void apply(OperationContext context) {
        context.findAnnotation(DisableTryItOut.class).ifPresent(annotation -> {
            context.operationBuilder()
                    .extensions(Collections.singletonList(new StringVendorExtension("x-disable-try-it-out", "true")));
        });
    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return SwaggerPluginSupport.pluginDoesApply(documentationType);
    }
}
  • 第三步:覆盖Swagger UI静态页面,注入按钮控制逻辑
    找到Swagger UI的入口页swagger-ui.html,如果是通过webjar引入的依赖,直接在项目resources/META-INF/resources/路径下新建同名文件即可覆盖webjar内的默认资源。在页面原有脚本末尾追加以下逻辑:
document.addEventListener('DOMContentLoaded', function() {
  const observer = new MutationObserver(() => {
    document.querySelectorAll('.opblock').forEach(block => {
      const opId = block.getAttribute('data-op-id');
      const spec = window.ui.spec().toJS();
      Object.values(spec.paths || {}).forEach(pathConfig => {
        Object.values(pathConfig).forEach(opConfig => {
          if (opConfig.operationId === opId && opConfig['x-disable-try-it-out'] === 'true') {
            const tryBtn = block.querySelector('.try-out__btn');
            if (tryBtn && !tryBtn.disabled) {
              tryBtn.disabled = true;
              tryBtn.style.opacity = '0.5';
              tryBtn.setAttribute('title', '该接口暂不支持在线调试');
            }
          }
        })
      })
    })
  })
  observer.observe(document.body, { subtree: true, childList: true });
})
  • 第四步:在需要禁用「Try it out」的接口方法上添加@DisableTryItOut注解即可生效
@ApiOperation("敏感数据导出接口")
@GetMapping("/export/sensitive")
@DisableTryItOut
public void exportSensitiveData() {
    // 业务逻辑
}

方案二:按HTTP请求方法粒度控制(适合粗粒度场景)

如果需要禁用按钮的接口刚好属于某一类单独的HTTP请求方法(比如所有DELETE方法、或自定义的请求方法),不需要精确到单个同方法类型的接口,可以直接在UI配置中排除对应方法,无需修改前端逻辑:

@Bean
public UiConfiguration swaggerUiConfig() {
    return UiConfigurationBuilder.builder()
            // 仅保留GET/POST/PUT方法的Try it out按钮,移除DELETE/PATCH方法的按钮
            .supportedSubmitMethods(new String[]{"get", "post", "put"})
            .build();
}

该方案局限性较强,只能按请求方法维度全局控制,无法对同请求方法下的不同接口做差异化配置。

兼容性说明

上述方案完全适配你使用的springfox-swagger2 2.9.2版本,不需要升级依赖,也不会破坏Swagger原有文档生成、接口展示的核心逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 04:24:16