Swagger的详细使用教程

一.Swagger的作用

swagger用于生成在线api文档和进行接口测试,是前后端联调中使用最多的工具

二.Swagger的详细使用步骤

1.引入Swagger依赖

<!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <scope>provided </scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <scope>provided </scope>
        </dependency>

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <scope>provided </scope>
       </dependency>

2.创建swagger配置类

3.若创建的swagger是新建的一个模块(若是在当前模块引入swager依赖,此步可以忽略),则:

(1)将swagger模块的坐标导入依赖到要使用swagger的模块中

(2)在启动类上添加@ComponentScan(basePackages={"swagger配置类所在的包路径"})

假设:swagger所在包:com.atguigu.servicebase

启动类所在包:com.atguigu.service

则配置为@ComponentScan(basePackages = {"com.atguigu"})

4.启动项目,访问http://ip:接口/swagger-ui.html进入swagger的控制台

若有弹窗问题,则要刷新maven,重启项目

5.接口测试

页面中已经显示了可以测试的接口,点击要测试的接口,value处输入参数,点击Try it out发送

6.swagger生成api文档的常用帮助注解:

以下这些注解用于生成api文档时,接口的提示信息

@Api(description = "讲师模块"):用在类上 @ApiOperation(value = "讲师列表"):用在方法上 @ApiParam(name = "id",value = "讲师id",required = true):用在参数上

@ApiModel:用在类上,标记类是swagger的解析类

属性: Value:为模型提供备用名称 description:提供详细的类描述

@ApiModelProperty:用在@A皮Model标记的类的属性上,

属性: Value: 属性简要说明

@ApiModel

效果如下:

经验分享 程序员 微信小程序 职场和发展