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

wav*_*cle 82 spring spring-mvc swagger

我有一个用简单的Spring编写的ReSTFul API(没有Spring Boot,没有花哨的东西!).我需要实现Swagger.到目前为止,互联网上的每一页都只让我感到疯狂,因为令人困惑的配置和臃肿的代码,我根本找不到便携式.

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

我必须澄清一点,我不是在寻找"为什么Swagger是最好的".我没有使用(并且我目前的任务不会使用)Spring Boot等.

woe*_*ler 117

Springfox(Swagger规范2.0,当前)

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

Maven依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
</dependency> 
Run Code Online (Sandbox Code Playgroud)

最小的实现看起来或多或少相同,但现在使用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();
    }

}
Run Code Online (Sandbox Code Playgroud)

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

注意:如果您没有使用Spring启动,那么您应该添加jackson-databind依赖项.由于springfox使用jackson进行数据绑定.

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

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.5.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Spring Boot,那么您的Web应用程序应自动获取必要的文件并显示UI http://myapp/swagger-ui.html(以前为:) 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/");
    }

}
Run Code Online (Sandbox Code Playgroud)

新的静态文档生成功能看起来也很不错,尽管我自己没有尝试过.

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

Swagger-SpringMVC的文档可能有点令人困惑,但它实际上非常容易设置.最简单的配置需要创建一个SpringSwaggerConfigbean并启用基于注释的配置(您可能已在Spring MVC项目中执行此操作):

<mvc:annotation-driven/>
<bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />
Run Code Online (Sandbox Code Playgroud)

但是,我认为使用the 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

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

<mvc:resources mapping="*.html" location="/" />
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 为了完整性:springfox'SwaggerConfig'示例中的'regex'方法来自'springfox.documentation.builders.PathSelectors.regex(String)'.如果花了我很长时间来弄明白;) (7认同)
  • 看起来UI网址现在是/myapp/swagger-ui.html而不是/ springfox (2认同)
  • 我冒昧地添加了`PathSelectors`来帮助人们在静态导入`regex`时苦苦挣扎 (2认同)
  • 值得注意的是:如果**完全**遵循这些说明,并且不使用 SpringBoot,那么由于从 Maven 检索到的 springfox 和 springfox-ui 库版本不同,您将收到运行时错误。相反,如果可能的话,从两者的最新版本开始(我写这篇文章时为“2.5.0”) (2认同)

Yur*_*kha 12

添加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>
Run Code Online (Sandbox Code Playgroud)

为spring-servlet.xml:

<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
Run Code Online (Sandbox Code Playgroud)

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

应该启用Swagger2

 @EnableSwagger2
 public class SwaggerConfiguration {
 }
Run Code Online (Sandbox Code Playgroud)