欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot 整合 Swagger

程序员文章站 2022-05-04 15:50:11
...

Why Swagger?

手写文档存在的问题

每当文档需要更新时,需要重新发送最新文档给前端,文档更新交流不及时。
接口返回结果不明确
不能直接在线测试接口,通常需要借助工具,比如:Postman
当接口文档太多时,不好分类管理

总结:前端、后段无法做到“及时协商,尽早解决”

引入Swagger相关依赖

1)、引入Spring整合Swagger依赖[SpringFox]

<!-- 引入Spring整合Swagger依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

2)、编写SpringFox配置类

/**
 * Spring 整合 Swagger配置类 [Docket:摘要]
 * @Author MoCha
 */
@Configuration
@EnableSwagger2
public class SpringFoxConfig {
    @Bean
    public Docket apiDocket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

访问地址:http://localhost:8080/v2/api-docs

  • @EnableSwagger2 enables SpringFox support for Swagger 2
  • DocumentationType.SWAGGER_2 tells the Docket bean that we are using version 2 of Swagger specification
  • select() creates a builder, which is used to define which controllers and which of their methods should be included in the generated documentation
  • apis() defines the classes (controller and model classes) to be included. Here we are including all of them, but you can limit them by a base package, class annotations and more
  • paths() allow you to define which controller's methods should be included based on their path mappings. We are now including all of them but you can limit it using regex and more
    Spring Boot 整合 Swagger

3)、引入Swagger-Ui依赖

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

4)、添加ApiInfo

@Configuration
@EnableSwagger2
public class SpringFoxConfig {
    @Bean
    public Docket apiDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(getApiInfo()); // 将ApiInfo加入到Docket中
    }

    private ApiInfo getApiInfo() {
        return new ApiInfo(
                "Spring Boot整合Swagger的API文档",
                "关于UserController的使用说明",
                "1.0.0",
                "https://gitee.com/MoChaYZF",
                new Contact("MoCha", "https://gitee.com/MoChaYZF", "aaa@qq.com"),
                "LICENSE",
                "LICENSE URL",
                Collections.emptyList()
        );
    }
}

访问方式:http://localhost:8080/swagger-ui.html

Spring Boot 整合 Swagger