如何在应用程序 url /swagger 中显示静态 swagger yaml 文件

How to display static swagger yaml file at application url /swagger

我创建了 yaml 文件(openapi 3.0.0 格式)作为我们 API 的文档。我想在 URL 处显示此(静态)swagger-ui yaml 文件,其中应用程序为 运行。像 http://localhost:8080/swagger-ui . Where is displayed graphical representation of yaml file (same as here 之类的东西)。 Yaml 文件放在项目的根文件夹中。

我是 运行 java 11 上的应用程序,springboot 2.1.5,building with maven。

我尝试使用

从代码生成 swagger yaml
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
    </dependency>
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.9.2</version>
    </dependency>

但这一个并不完美(缺少默认值、描述..)

我尝试了 spring static resources 但没有成功。问题是 yaml 文件不是 html.

有没有其他(也许更好)的方法,如何显示 api 文档?

你也需要添加 swagger UI 依赖。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

然后您可以使用

访问 swagger ui
http://localhost:9090/swagger-ui.html#/

尝试将此添加到您的方法中,

public void yourMethod(@ApiParam(name = "id", required = true, value = "The id of the site", defaultValue = "3F7B07E2") String id)

我们能够使用@Configugarion 完成这项任务class

@Configuration
    public class SwaggerConfiguration implements WebMvcConfigurer {

      private final String swaggerUILocation = "whatEverLocationYouWant";
      private final String swaggerApiDocsLocation = "whatEverLocationYouWant";

      @Override
      public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(swaggerUILocation + "**")
            .addResourceLocations("classpath:/swagger-ui/");
        registry.addResourceHandler(swaggerApiDocsLocation + "**")
            .addResourceLocations("classpath:/swagger/");
      }
    }

然后我们使用swagger-ui jar 文件,将其解压缩到resources 文件夹中并在此处替换index.html 文件中的一行:

<script>
      window.onload = function () {
        // Begin Swagger UI call region
        const ui = SwaggerUIBundle({
          url: "placeHereExactLinkToYourYamlFile",
          dom_id: '#swagger-ui',
          deepLinking: true,
          presets: [
            SwaggerUIBundle.presets.apis,
            SwaggerUIStandalonePreset
          ],
          plugins: [
            SwaggerUIBundle.plugins.DownloadUrl
          ],
          layout: "StandaloneLayout"
        })
        // End Swagger UI call region

        window.ui = ui
      }
    </script>

大摇大摆的 html 可见并且正在应用程序旁边工作。