在Spring Boot设置Swagger 2 - Baeldung


Swagger 2版本变动很大,无法像前面版本容易集成到Spring Boot中。
步骤:
1. 我们将使用Swagger规范的Springfox实现。最新版本可以在Maven Central上找到  。要将其添加到我们的Maven项目中,我们需要pom.xml文件中的依赖项。

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

2. Spring Boot自动配置:

@Configuration
@EnableSwagger2
public class SpringFoxConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

Swagger 2通过@ EnableSwagger2注释启用。
定义Docket bean 之后,其select()方法将返回ApiSelectorBuilder的实例,该实例提供了一种控制Swagger公开的端点的方法。
可以在RequestHandlerSelectors和PathSelectors的帮助下配置用于选择RequestHandler的谓词。两者都使用any()可以通过Swagger获得整个API的文档。
此配置足以将Swagger 2集成到现有的Spring Boot项目中。对于其他Spring项目,需要进行一些其他调整。

3. Swagger UI是一个内置解决方案,它使用户与Swagger生成的API文档进行交互变得更加容易。要使用Swagger UI,还需要一个附加的Maven依赖项:

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

现在,您可以通过访问http://localhost:8080/your-app-root/swagger-ui.html在浏览器中对其进行测试

更深入玩法点击标题见原文。请查看此GitHub模块见源码实现