swagger2使用示例 - 基于springboot整合入门篇

前言

随着互联网的技术的发展,前后端分离对于开发人员来说毋庸置疑是一个好的发展。
前端人员只负责前端界面,后端人员也只负责后端业务逻辑处理。但是在团队开发中,总总避免不了前端人员和后端人员缺少沟通情况下,难免会在接口文档上出现错误。
就是在这种情况下,swagger 就是为了这种情况而出现的。通过后端swagger提供的方法注释写接口文档,生成页面文档。再让前端人员测试接口。
在网上资料学习的过程中,了解到swagger是一种规范,是用于Spring基础上的一种规范实现。
也是为Spring提供了服务。

1.Swagger2的好处

Swagger2作为一个规范和完整的框架,可以用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
-接口文档在线生成,文档实时为业务需求变动,节省维护成本
-支持在线接口测试
-便于保存、整理、查阅和调试API接口

2.基于Springboot 整合swagger2

2.1 swagger2 注解使用示例

controller 类里面@注解

  • @Api:用在请求的类上,说明该类的作用
@Api:用在请求的类上,说明该类的作用
    tags="说明该类的作用"
    value="该参数没什么意义,所以不需要配置"

-@ApiOperation:用在请求的方法上,说明方法的作用

@ApiOperation:"用在请求的方法上,说明方法的作用"
    value="说明方法的作用"
    notes="方法的备注说明"

-@ApiImplicitParam: 用在请求的方法上,一个参数说明
-@ApiImplicitParams:用在请求的方法上,包含一组参数说明

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值

controller演示上面几个@注解

@Api(tags = "预约业务处理控制类")
@RestController
@RequestMapping("/appoint")
public class AppointController {

    @Autowired
    private AppointmentMapper appointmentMapper;

     /**
     * 查询预约id
     * @param appointId
     * @return
     */
    @ApiOperation(value = "获取预约信息",notes = "根据url的appointId来获取预约信息")
    @ApiImplicitParam(name = "appointId",value = "预约id",dataType = "String",paramType = "path")
    @RequestMapping(value = "/getByAppoint/{appointId}",method = RequestMethod.GET)
    public ResultVo getByAppointById(@PathVariable(value = "appointId")
                                     String appointId){
        Appointment appointment = appointmentMapper.selectByPrimaryKey(appointId);
        return ResultVoUtil.success(appointment);
    }


    /**
     * 添加信息
     * @param appointment
     * @return
     */
    @ApiOperation(value = "添加预约信息",notes = "注意格式参数")
    @ApiImplicitParam(paramType = "body")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ResultVo Add( Appointment appointment){
        int i = appointmentMapper.insert(appointment);
        if (i > 0 ){
            return ResultVoUtil.success();
        }
        return null;
    }

    /**
     * 删除预约
     * @param appointId
     * @return
     */
    @ApiOperation(value ="删除预约信息",notes = "根据url的appointId带来删除预约信息")
    @ApiImplicitParam(name = "appointId",value = "预约id",dataType = "String",paramType = "path")
    @RequestMapping(value = "/deleteByAppoint/{appointId}",method = RequestMethod.DELETE)
    public ResultVo deleteByProductId(@PathVariable(value = "appointId")
                                                  String appointId){


        int i =  appointmentMapper.deleteByPrimaryKey(appointId);
        if (i > 0 ){
           return ResultVoUtil.success();
        }
        return null;
    }

    /**
     * 修改预约
     * @param appointment
     * @return
     */
    @ApiOperation(value = "修改预约信息",notes = "注意格式参数")
    @ApiImplicitParam(paramType = "body")
    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    public ResultVo Update( Appointment appointment){
        int i = appointmentMapper.updateByPrimaryKey(appointment);
        if (i > 0 ){
        return     ResultVoUtil.success();
        }
        return null;
    }
 
// 用于演示 ApiImplicitParams  本方法不属于本controller,可以把它注释掉
  @ApiOperation(value = "添加用户",notes = "注册格式参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "nickname",value = "用户账号",required = true,dataType = "String"),
            @ApiImplicitParam(name = "openId",value = "用户密码",required = true,dataType = "String")
    })
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ResultVo login(String openId,String nickname ){
        WeChatUser weChatUser = new WeChatUser();
        weChatUser.setOpenId(openId);
        weChatUser.setNickName(nickname);
        WeChatUser select = userMapper.selectOne(weChatUser);
        return ResultVoUtil.success();      
    }
}

实体类@注解

-@ApiModel:用于响应类上,表示一个返回响应数据的信息

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

演示

@Data
@Accessors(chain = true)
@Table(name = "appoint_ment")
@ApiModel(value = "appointmentInfo",description = "用于预约服务模块")
public class Appointment implements Serializable {
    
    @Id
    @KeySql(useGeneratedKeys = true) //回显
    private String appointId;

    /**名字*/
    @ApiModelProperty(name = "appointName",value = "预约服务名",required = true)
    private String appointName;

    /**日期*/
    @ApiModelProperty(name = "appointWeek",value = "预约星期",required = true)
    private Date appointWeek;

    /**时间 08:00*/
    @ApiModelProperty(name = "appointTime",value = "预约时间",required = true)
    private String appointTime;

    /**单价*/
    @ApiModelProperty(name = "appointPrice",value = "服务价格",required = true)
    private BigDecimal appointPrice;

    /** 状态,0正常 1下架*/
    @ApiModelProperty(name = "appointStatus",value = "服务状态: 0-正常 1-伪删除")
    private Integer appointStatus;

    /**类目编号*/
    @ApiModelProperty(name = "categoryType",value = "服务类型",required = true)
    private Integer categoryType;
    
    private Date createTime;

    private Date updateTime;
    
}

2.2 maven pom.xml依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com,mi</groupId>
    <artifactId>springboot-swagger-demo-1</artifactId>
    <version>1.0-SNAPSHOT</version>

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

    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

        <!--通用mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--MySQL依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- swagger2  主要的两个依赖包-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
    </dependencies>
</project>
-swagger2 主要的两个依赖包

springfox-swagger2和springfox-swagger-ui

2.3 application.yml 配置文件

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    username: root
    password: 123456
    url: jdbc:mysql://localhost/haircut?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
  mvc:
    static-path-pattern: /**
mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml
  type-aliases-package: com.mi.domain
server:
  servlet:
    context-path: /swagger
  port: 8090

2.4 mapper通用接口

在这里演示2个mapper接口
-预约表

/**
 * @author : Rong
 * @date : 2019/2/12
 * @Desc: 预约表
 */
public interface AppointmentMapper extends Mapper<Appointment> {
}

2.5 封装返回数据类

@Data
public class ResultVo<T> {

    /**错误码*/
    private Integer code;

    /**提示信息*/
    private String msg ;

    /**具体内容*/
    private T data;
}

2.6 封装返回数据工具类

public class ResultVoUtil {
    
    public static ResultVo success(Object object){
        ResultVo resultVo = new ResultVo();
        resultVo.setData(object);
        resultVo.setCode(0);
        resultVo.setMsg("成功");
        return resultVo;
    }

    public static ResultVo success(){
        return success(null);
    }

    public static ResultVo error(Integer code, String msg){
        ResultVo resultVo = new ResultVo();

        resultVo.setCode(code);
        resultVo.setMsg(msg);
        return resultVo;
    }
}

2.7 创建swagger2 配置启动类

@Configuration
public class swaggerConfiguration {
    @Bean
    public Docket createDocketApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mi"))
                .paths(PathSelectors.any())
                .build();
    }

    //  API 信息
    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("xxxx服务文档")
                .description("XXX API 接口文档")
                .version("1.0")
                .build();
    }
}

-Docket : 是用来生成文档的函数,其下有包含该调用的方法
-apiInfo:是用来描述文档的基本信息
-select:用来控制哪些接口暴露给 Swagger 来展现
-apis: 会扫描该包下所有的定义controller的API
-paths: 任何url请求文档

3. 启动项目

SpringBoot 启动成功后,访问 http://localhost:8090/swagger/swagger-ui.html

3.1 swagger-ui 界面

image.png

从上面图片可以看到swagger配置类生成的文档名称

3.2 展开方法请求

image.png

展开开后可以看到接口列表,页面会列出该类中定义的所有接口。点击任意接口,可查看该接口的 url 路径、请求类型、参数描述和返回码说明等信息。

点击右上角的 “Try it out!”按钮,录入请求信息,可以测试接口请求调用!

4.swagger2 注解类型基本介绍

-@Api:修饰整个类,描述Controller的作用
-@ApiOperation:描述一个类的一个方法,或者说一个接口
-@ApiParam:单个参数描述
-@ApiModel:用对象来接收参数
-@ApiProperty:用对象接收参数时,描述对象的一个字段
-@ApiResponse:HTTP响应其中1个描述
-@ApiResponses:HTTP响应整体描述
-@ApiIgnore:使用该注解忽略这个API
-@ApiError :发生错误返回的信息
-@ApiImplicitParam:描述一个请求参数,可以配置参数的中文含义,还可以给参数设置默认值
-@ApiImplicitParams:描述由多个 @ApiImplicitParam 注解的参数组成的请求参数列表

有兴趣的同学可以去了解其它注解的用途。

项目github地址源码:https://github.com/mi499938150/springboot-swagger-demo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容