SpringBoot集成Swagger生成API文档

  • 本文主要介绍基于springboot框架下使用swagger生成api文档的基本使用方法
  • 基于REST风格的接口接口规范来进行代码编写,加上自动化的api文档简直不要太舒服,下面是基本的使用,以及解释
  • 在传统开发中我们经常使用word来进行接口文档的编写,这种方法很繁琐,随着时间的增加接口的变化和繁多也会导致文档变得难以维护和停止维护,这对于刚入职公司的新人来说是非常的不友好的,swagger可以根据你接口的参数变化随着你服务器的启动来进行不断的更新文档;
  • 首先需要搭建一个springboot的项目,此处省略;
  • pom依赖
<!--swagger-->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>
  • swagger的配置相当简单,需要作为一个配置类来进行加载,以下为代码
package com.sunyw.xyz.statics;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.builders.PathSelectors;
/**
 * @description:swaggerAPI文档配置属性类
 * @author: sunyw
 * @time: 2020-02-25 13:13
 */
@Configuration
@EnableSwagger2
public class WeatherSwagger {
    @Bean
    public Docket createSwagger(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sunyw.xyz"))
                .paths(PathSelectors.regex("/api/.*"))
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Weather天气平台API文档")
                .description("sunyw")
                .termsOfServiceUrl("https://xxx.xyz")
                .version("1.0")
                .build();
    }
}

  • 然后重新启动项目,访问http://localhost:7000/swagger-ui.html
  • 效果图
    在这里插入图片描述
  • swagger的测试平台,点开后面的接口即可进行接口测试
    在这里插入图片描述
  • 测试
    在这里插入图片描述
  • 有帮助的话帮忙点个👍
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值