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

Old*_*eer 5 java swagger-ui spring-boot

我创建了 yaml 文件(openapi 3.0.0 格式)作为我们 API 的文档。我想在应用程序运行的 URL 上显示这个(静态)swagger-ui yaml 文件。类似http://localhost:8080/swagger-ui 的东西。yaml 文件的图形表示在哪里显示(与此处相同)。Yaml 文件放置在项目的根文件夹中。

我在 java 11, springboot 2.1.5 上运行应用程序,使用 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>
Run Code Online (Sandbox Code Playgroud)

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

我试过 spring 静态资源但没有成功。问题是 yaml 文件不是 html。

还有另一种(也许更好)的方式,如何显示 api 文档?

Old*_*eer 0

我们能够使用 @Configugarion 类完成此任务

@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/");
      }
    }
Run Code Online (Sandbox Code Playgroud)

然后我们使用 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>
Run Code Online (Sandbox Code Playgroud)

swagger html 是可见的并且正在应用程序旁边工作。