首页 > 解决方案 > springdoc swagger-ui HTML页面如何配置自定义URL?

问题描述

将 springdoc-openapi-ui 依赖项添加到我的 Spring 项目(不是 Spring Boot)后,生成 OpenAPI V3 文档,可以使用默认的 swagger-ui 页面查看:localhost:8080/swagger-ui.html. 因为 springdoc 文档替换了以前的 Swagger 文档,所以我想让它在同一个 URL 上可用,localhost:8080/docs/index.html. 根据 springdoc 文档,我得到的印象可以通过使用以下springdoc.swagger-ui.path选项来完成application.properties

springdoc.swagger-ui.path=/docs/index.html

但是,我希望能够通过转到localhost:8080/docs/index.html404 来导航到 API 文档,localhost:8080/swagger-ui.html但它仍然有效,但现在重定向到http://localhost:8080/docs/swagger-ui/index.html?configUrl=/restapi/v3/api-docs/swagger-config.

如何配置我的项目也使 swagger-ui 页面通过自定义 URL 可用,即localhost:8080/docs/index.html而不是默认URL localhost:8080/swagger-ui.html

编辑

在尝试更多使其正常工作并在线查看可用信息后,例如 springdoc常见问题解答(H3AR7B3A7 在答案中提到),我无法使其正常工作。我决定采用不同的解决方案,它应该具有相同的效果。该springdoc.swagger-ui.path选项允许指定自定义 URL,但据我了解,转到自定义 URL 会将用户重定向到标准localhost:8080/swagger-ui.html页面。所以现在手动配置重定向:

@RequestMapping("/docs/index.html")
public void apiDocumentation(HttpServletResponse response) throws IOException {
  response.sendRedirect("/swagger-ui.html");
}

标签: springspringdocspringdoc-openapi-ui

解决方案


Spring Boot 2.5.6我对and有类似的任务springdoc-openapi-webflux-ui 1.5.12。我为自己找到了几种可能的解决方案。也许它对其他人有帮助。


springdoc.swagger-ui.path直接设置

直接的方法是设置属性springdoc.swagger-ui.path=/custom/pathswagger如果您可以在应用程序中硬编码路径,它将完美运行。


覆盖springdoc.swagger-ui.path属性

swagger-ui您可以使用 以编程方式更改默认路径ApplicationListener<ApplicationPreparedEvent>springdoc.swagger-ui.path=/custom/path这个想法很简单——在 Spring Boot 应用程序启动之前覆盖。

@Component
public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> {

    @Override
    public void onApplicationEvent(final ApplicationPreparedEvent event) {
        ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
        Properties props = new Properties();
        props.put("springdoc.swagger-ui.path", swaggerPath());
        environment.getPropertySources()
                .addFirst(new PropertiesPropertySource("programmatically", props));
    }

    private String swaggerPath() {
        return "/swagger/path"; //todo: implement your logic here.
    }
}

在这种情况下,您必须在应用程序启动之前注册监听器:

@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "APIs", version = "0.0.1", description = "APIs v0.0.1"))
public class App {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(App.class);
        application.addListeners(new SwaggerConfiguration());
        application.run(args);
    }
}

使用控制器重定向</h3>

您还可以注册自己的控制器并进行简单的重定向(与您的建议相同,但在我的情况下,我需要使用该WebFlux方法):

@RestController
公共类 SwaggerEndpoint {

    @GetMapping("/自定义/路径")
    公共 Mono<Void> api(ServerHttpResponse 响应) {
        response.setStatusCode(HttpStatus.PERMANENT_REDIRECT);
        response.getHeaders().setLocation(URI.create("/swagger-ui.html"));
        返回 response.setComplete();
    }
}

这种方法的问题 - 如果您通过地址调用它,您的服务器仍然会响应"/swagger-ui.html"


推荐阅读