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

问题描述 投票:79回答:3

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

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

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

spring spring-mvc swagger
3个回答
116
投票

Springfox (Swagger spec 2.0, current)

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

Maven依赖

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

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

}

您的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>

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

}

新的static documentation generation功能也看起来很不错,虽然我自己没有尝试过。

Swagger-SpringMVC (Swagger spec 1.2, older)

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

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

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

}

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

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

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

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

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


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>

为spring-servlet.xml:

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

或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 {
 }

1
投票

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

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

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

或者用于JAX-RS

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

© www.soinside.com 2019 - 2024. All rights reserved.