Spring Boot 整合 Swagger

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
    在这里插入图片描述

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", "1358192165@qq.com"),
                "LICENSE",
                "LICENSE URL",
                Collections.emptyList()
        );
    }
}

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

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值