在 Spring MVC 应用程序中实现 Swagger 的“简单”方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26720090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:11:02  来源:igfitidea点击:

A 'simple' way to implement Swagger in a Spring MVC application

springspring-mvcswagger

提问by wavicle

I have a ReSTFul API written in simple Spring (no Spring Boot, no fancy stuff!). I need to implement Swagger into this. So far, EVERY page on the internet has only driven me crazy with confusing configurations and bloated code that I did not find portable at all.

我有一个用简单的 Spring 编写的 ReSTFul API(没有 Spring Boot,没有花哨的东西!)。我需要在其中实施 Swagger。到目前为止,互联网上的每个页面都只会让我发疯,因为我根本无法找到可移植的令人困惑的配置和臃肿的代码。

Does anyone have a sample project (or a set of detailed steps) that can help me accomplish this? In particular, I am looking for a good sample that uses swagger-springmvc. I know it has 'samples', but at best, the esoteric code is discouraging.

有没有人有可以帮助我完成此任务的示例项目(或一组详细步骤)?特别是,我正在寻找一个使用 swagger-springmvc 的好样本。我知道它有“样本”,但充其量,深奥的代码令人沮丧。

I must clarify that I am not looking for "why Swagger is simply the best". I am not using (and for my current task will not use) Spring Boot or such.

我必须澄清,我不是在寻找“为什么 Swagger 是最好的”。我没有使用(并且对于我当前的任务不会使用)Spring Boot 等。

回答by woemler

Springfox (Swagger spec 2.0, current)

Springfox(Swagger 规范 2.0,当前)

Springfoxhas replaced Swagger-SpringMVC, and now supports both Swagger specs 1.2 and 2.0. The implementation classes have changed, allowing for some deeper customization, but with some work. The documentationhas improved, but still needs some details added for advanced configuration. The old answer for the 1.2 implementation can still be found below.

Springfox已取代 Swagger-SpringMVC,现在支持 Swagger 规范 1.2 和 2.0。实现类已经改变,允许进行一些更深入的定制,但需要做一些工作。该文档有所改善,但仍需要一些细节增加了高级配置。1.2 实现的旧答案仍然可以在下面找到。

Maven dependency

Maven 依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
</dependency> 

The bare-minimum implementation looks more-or-less the same, but now uses the Docketclass instead of the SwaggerSpringMvcPluginclass:

最低限度的实现看起来或多或少相同,但现在使用Docket类而不是SwaggerSpringMvcPlugin类:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.regex("/api/.*"))
            .build()
            .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("TITLE")
            .description("DESCRIPTION")
            .version("VERSION")
            .termsOfServiceUrl("http://terms-of-services.url")
            .license("LICENSE")
            .licenseUrl("http://url-to-license.com")
            .build();
    }

}

Your Swagger 2.0 API documentation will now be available at http://myapp/v2/api-docs.

您的 Swagger 2.0 API 文档现在可以在http://myapp/v2/api-docs.

Note : If you are not using Spring boot then you should add Hymanson-databind dependency. Since springfox uses Hymanson for databinding.

注意:如果您不使用 Spring boot,那么您应该添加 Hymanson-databind 依赖项。由于 springfox 使用 Hymanson 进行数据绑定。

Adding Swagger UI support is even easier now. If you are using Maven, add the following dependency for the Swagger UI webjar:

现在添加 Swagger UI 支持更加容易。如果您使用的是 Maven,请为 Swagger UI webjar 添加以下依赖项:

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

If you are using Spring Boot, then your web app should automatically pick up the necessary files and show the UI at http://myapp/swagger-ui.html(formerly: http://myapp/springfox). If you are not using Spring Boot, then as yuriy-tumakha mentions in the answer below, you will need to register a resource handler for the files. The Java configuration looks like this:

如果您使用的是 Spring Boot,那么您的 Web 应用程序应该会自动选取必要的文件并在http://myapp/swagger-ui.html(以前的:)处显示 UI http://myapp/springfox。如果您没有使用 Spring Boot,那么正如 yuriy-tumakha 在下面的答案中提到的,您将需要为文件注册一个资源处理程序。Java 配置如下所示:

@Configuration
@EnableWebMvc
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

}

The new static documentation generationfeature also looks quite nice, though I have not tried it out myself.

新的静态文档生成功能看起来也很不错,虽然我自己还没有尝试过。

Swagger-SpringMVC (Swagger spec 1.2, older)

Swagger-SpringMVC(Swagger 规范 1.2,较旧)

The documentation for Swagger-SpringMVCcan be a little bit confusing, but it is actually incredibly easy to set up. The simplest configuration requires creating a SpringSwaggerConfigbean and enabling annotation-based configuration (which you probably already do in your Spring MVC project):

Swagger-SpringMVC的文档可能有点令人困惑,但它实际上非常容易设置。最简单的配置需要创建一个SpringSwaggerConfigbean 并启用基于注解的配置(您可能已经在 Spring MVC 项目中这样做了):

<mvc:annotation-driven/>
<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />

However, I think it is well worth it to take the extra step of defining a custom Swagger configuration using the SwaggerSpringMvcPlugin, instead of the previous XML-defined bean:

但是,我认为使用SwaggerSpringMvcPlugin, 而不是以前的 XML 定义的 bean来定义自定义 Swagger 配置的额外步骤是非常值得的:

@Configuration
@EnableSwagger
@EnableWebMvc
public class SwaggerConfig {

    private SpringSwaggerConfig springSwaggerConfig;

    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
        this.springSwaggerConfig = springSwaggerConfig;
    }

    @Bean
    public SwaggerSpringMvcPlugin customImplementation(){

        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                .apiInfo(apiInfo())
                .includePatterns(".*api.*"); // assuming the API lives at something like http://myapp/api
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
            .title("TITLE")
            .description("DESCRIPTION")
            .version("VERSION")
            .termsOfServiceUrl("http://terms-of-services.url")
            .license("LICENSE")
            .licenseUrl("http://url-to-license.com")
            .build();
    }

}

When you run your application, you should now see your API spec created at http://myapp/api-docs. To get the fancy Swagger UI set up, you need to clone the static files from the GitHub projectand put them in your project. Make sure your project is configured to serve the static HTML files:

运行应用程序时,您现在应该会看到在http://myapp/api-docs. 要设置精美的 Swagger UI,您需要从GitHub 项目中克隆静态文件并将它们放入您的项目中。确保您的项目配置为提供静态 HTML 文件:

<mvc:resources mapping="*.html" location="/" />

Then edit the index.htmlfile at the top level of the Swagger UI distdirectory. Towards the top of the file, you'll see some JavaScript that refers to the api-docsURL of another project. Edit this to point to your project's Swagger documentation:

然后index.html在 Swagger UIdist目录的顶层编辑该文件。在文件顶部,您将看到一些引用api-docs另一个项目 URL 的JavaScript 。编辑它以指向您项目的 Swagger 文档:

  if (url && url.length > 1) {
    url = url[1];
  } else {
    url = "http://myapp/api-docs";
  }

Now when you navigate to http://myapp/path/to/swagger/index.html, you should see the Swagger UI instance for your project.

现在,当您导航到 时http://myapp/path/to/swagger/index.html,您应该会看到项目的 Swagger UI 实例。

回答by Yuriy Tumakha

Springfox Swagger UI works for me after adding WebJar dependency and resource mappings. http://www.webjars.org/documentation#springmvc

在添加 WebJar 依赖项和资源映射后,Springfox Swagger UI 对我有用。 http://www.webjars.org/documentation#springmvc

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.2.2</version>
    </dependency>
    <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>bootstrap</artifactId>
        <version>3.3.5</version>
    </dependency>

spring-servlet.xml:

弹簧servlet.xml:

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

or Spring Annotation https://github.com/springfox/springfox-demos/blob/master/spring-java-swagger/src/main/java/springfoxdemo/java/swagger/SpringConfig.java

或 Spring 注解 https://github.com/springfox/springfox-demos/blob/master/spring-java-swagger/src/main/java/springfoxdemo/java/swagger/SpringConfig.java

Swagger2 should be enabled

应该启用 Swagger2

 @EnableSwagger2
 public class SwaggerConfiguration {
 }

回答by kkhipis

You can also consider using swagger-maven-plugin to generate swagger.json and copy it to yours static swagger-ui.

您也可以考虑使用 swagger-maven-plugin 生成 swagger.json 并将其复制到您的静态 swagger-ui。

Please check simple sample of working plugin with Spring MVC annotations on this repo:

请在此 repo 上使用 Spring MVC 注释检查工作插件的简单示例:

https://github.com/khipis/swagger-maven-example

https://github.com/khipis/swagger-maven-example

or for JAX-RS

或用于 JAX-RS

https://github.com/kongchen/swagger-maven-example

https://github.com/kongchen/swagger-maven-example