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

SpringBoot中通过配置Bean为swagger-ui配置服务变量实现URL动态修改

实现方法

你的实现思路是对的,只需要在构建io.swagger.v3.oas.models.OpenAPI Bean时,手动构造带变量定义的Server对象赋值给servers字段,就能完全复现YAML配置的效果,Swagger UI会自动识别服务变量,渲染出可动态修改URL的输入控件。

前置依赖

确保项目使用springdoc-openapi依赖(已停止维护的Springfox不支持该配置方式),以Spring WebMVC项目为例,Maven依赖如下:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.3.0</version>
</dependency>

完整配置代码

编写OpenAPI配置类,手动构造带变量的服务配置:

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.oas.models.servers.ServerVariable;
import io.swagger.v3.oas.models.servers.ServerVariables;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI customOpenAPI() {
        // 定义URL变量,对应YAML中variables下的foo配置
        ServerVariable fooVar = new ServerVariable()
                ._default("bar"); // 设置变量默认值

        // 构造服务地址配置
        Server targetServer = new Server()
                .url("https://{foo}.com")
                .variables(new ServerVariables().addServerVariable("foo", fooVar));

        return new OpenAPI()
                .info(new Info().title("Foo Service").version("v1.0"))
                .servers(List.of(targetServer));
    }
}

注意事项

  • ServerVariables中设置的变量名必须和URL模板里{}包裹的占位符名称完全一致,否则变量无法被UI识别
  • 如果页面出现多余的默认服务地址选项,可以在application.yml中添加如下配置关闭SpringDoc自动生成的服务地址:
    springdoc:
      api-docs:
        servers: []
    
  • 如需限制变量可选值,可调用ServerVariable的addEnumItem()方法追加可选值,UI会自动将输入控件替换为下拉选择框:
    fooVar.addEnumItem("bar").addEnumItem("test").addEnumItem("prod");
    
  • 配置完成重启项目后,即可在Swagger UI看到和原YAML配置完全一致的效果:
    带服务变量输入控件的Swagger UI

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 04:21:14