使用配置bean使用服务器变量配置swagger-ui

gywdnpxw  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(81)

在我的spring Boot 项目中,我有一个由swagger UI使用的API的openapi3 yaml定义。我需要能够在使用UI时动态更改服务器URL的一部分,我能够在yaml中配置它

openapi: 3.0.1
info:
  title: Foo Service
  version: v1.0
servers:
  - url: https://{foo}.com
    variables:
      foo:
        default: bar

字符串
这使得UI看起来像

现在,我想停止使用yamls来定义API,而是使用注解和配置bean。我觉得应该在io.swagger.v3.oas.models.OpenAPI bean中设置servers字段,但是我不知道该怎么做,因为我想让swagger UI动态更改URL。
任何指导将不胜感激

fd3cxomn

fd3cxomn1#

让我们试试这个,我从github上找到了这个代码

import io.swagger.v3.oas.models.OpenAPI;
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;

@Configuration
public class OpenApiGeneratorConfig {

    @Bean
    public OpenAPI defineOpenApi() {
        return new OpenAPI()
                .info(defineInfo())
                .components(defineComponents())
                .addServersItem(defineServers());
    }

...

    private Server defineServers() {
        return new Server().url("http://{IP_Address}:8080/my-app")
                           .description("My APP REST API Server")
                           .variables(
                                   new ServerVariables().addServerVariable("IP_Address", new ServerVariable()
                                           //._default("www.example.com")
                                           ._default("localhost")
                                           .description("IP address of My APP REST API Server")
                                   )
                           );
    }
}

字符串

相关问题