在Spring MVC应用程序中实现Swagger的“简单"方法 [英] A 'simple' way to implement Swagger in a Spring MVC application

查看:99
本文介绍了在Spring MVC应用程序中实现Swagger的“简单"方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

有人有一个示例项目(或一组详细的步骤)可以帮助我实现这一目标吗?特别是,我正在寻找使用swagger-springmvc的良好示例.我知道它有样本",但充其量来说,深奥的代码令人沮丧.

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就是最好的".我没有使用(或当前的任务将不使用)Spring Boot之类的东西.

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.

推荐答案

Springfox(Swagger spec 2.0,当前)

Springfox 取代了Swagger-SpringMVC,现在同时支持Swagger规范1.2和2.0.实现类已更改,可以进行一些更深入的自定义,但需要做一些工作. 文档已得到改进,但仍需要添加一些详细信息以进行高级配置.仍可在下面找到1.2实现的旧答案.

Springfox (Swagger spec 2.0, current)

Springfox has 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 documentation has improved, but still needs some details added for advanced configuration. The old answer for the 1.2 implementation can still be found below.

Maven依赖

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

最低实现看起来大致相同,但是现在使用Docket类而不是SwaggerSpringMvcPlugin类:

The bare-minimum implementation looks more-or-less the same, but now uses the Docket class instead of the SwaggerSpringMvcPlugin class:

@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();
    }

}

您的Swagger 2.0 API文档现在将在http://myapp/v2/api-docs上提供.

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

注意:如果您不使用Spring Boot,则应该添加jackson-databind依赖项.由于springfox使用jackson进行数据绑定.

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

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

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

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

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

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:

@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 generation feature also looks quite nice, though I have not tried it out myself.

Swagger-SpringMVC 的文档可能会有些混乱,但实际上令人难以置信易于设置.最简单的配置需要创建一个SpringSwaggerConfig bean并启用基于注释的配置(您可能已经在Spring MVC项目中进行了此配置):

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

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

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

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:

@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();
    }

}

运行应用程序时,现在应该可以在http://myapp/api-docs看到创建的API规范.要设置精美的Swagger UI,您需要从 GitHub项目,并将其放入您的项目中.确保将您的项目配置为提供静态HTML文件:

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 project and put them in your project. Make sure your project is configured to serve the static HTML files:

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

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

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

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

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

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

这篇关于在Spring MVC应用程序中实现Swagger的“简单"方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆