前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Swagge里面的必会知识(最全,精美版)

Swagge里面的必会知识(最全,精美版)

作者头像
CaesarChang张旭
发布2021-01-26 15:03:15
7580
发布2021-01-26 15:03:15
举报
文章被收录于专栏:悟道

1简介

简介

Swagger是一款目前世界最流行的API管理工具。目前Swagger已经形成一个生态圈,能够管理API的整个生命周期,从设计、文档到测试与部署。Swagger有几个重要特性:

  • 代码侵入式注解
  • 遵循YAML文档格式
  • 非常适合三端(PC、iOS及Android)的API管理,尤其适合前后端完全分离的架构模式。
  • 减少没有必要的文档,符合敏捷开发理念
  • 功能强大

作用

  • 接口的文档在线自动生成
  • 功能测试

优点

1. 大大减少前后端的沟通 2. 方便查找和测试接口 3. 提高团队的开发效率 4. 方便新人了解项目

2配置swagger

引入依赖(哪个分布式项目需要在线生成接口,就需要引入)

代码语言:javascript
复制
<!-- swagger -->

<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>

配置类

代码语言:javascript
复制
package com.zx.upload.config;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;




import springfox.documentation.service.ApiInfo;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**

 * Swagger 配置文件

 */

@Configuration

@EnableSwagger2

public class SwaggerConfig {

    @Bean

    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)

                .apiInfo(apiInfo())

                .select()

                .apis(RequestHandlerSelectors.basePackage("com.zx")) //swagger搜索的包

                .paths(PathSelectors.any()) //swagger路径匹配

                .build();

    }

    private ApiInfo apiInfo() {

        return new ApiInfoBuilder()

                .title("文件上传文档")

                .description("使用FastDfs文件上传")

                .version("version 1.0")

                .build();

    }

}

3常用注解

swagger通过在controller中,声明注解,API文档进行说明

1、@Api():用在请求的类上,表示对类的说明,也代表了这个类是swagger2的资源

参数:

  • tags:说明该类的作用,参数是个数组,可以填多个。
  • value="该参数没什么意义,在UI界面上不显示,所以不用配置"
  • description = "用户基本信息操作"

2、@ApiOperation():用于方法,表示一个http请求访问该方法的操作

参数:

  • value="方法的用途和作用"
  • notes="方法的注意事项和备注"
  • tags:说明该方法的作用,参数是个数组,可以填多个。
  • 格式:tags={"作用1","作用2"} (在这里建议不使用这个参数,会使界面看上去有点乱,前两个常用)

3、@ApiModel():用于响应实体类上,用于说明实体作用

参数:

description="描述实体的作用"

4、@ApiModelProperty:用在属性上,描述实体类的属性

参数:

value="用户名" 描述参数的意义 name="name" 参数的变量名 required=true 参数是否必选

5、@ApiImplicitParams:用在请求的方法上,包含多@ApiImplicitParam

6、@ApiImplicitParam:用于方法,表示单独的请求参数

参数:

  1. name="参数名称"
  2. value="参数说明"
  3. dataType="数据类型"

paramType="query" 表示参数放在哪里

· header 请求参数的获取:@RequestHeader · query 请求参数的获取:@RequestParam · path(用于restful接口) 请求参数的获取:@PathVariable · body(不常用) · form(不常用)

defaultValue="参数的默认值"

required="true" 表示参数是否必须传

7、@ApiParam():用于方法,参数,字段说明 表示对参数的要求和说明

参数:

  1. name="参数名称"
  2. value="参数的简要说明"
  3. defaultValue="参数默认值"
  4. required="true" 表示属性是否必填,默认为false

8、@ApiResponses:用于请求的方法上,根据响应码表示不同响应

一个@ApiResponses包含多个@ApiResponse

9、@ApiResponse:用在请求的方法上,表示不同的响应

参数

code="404" 表示响应码(int型),可自定义 message="状态码对应的响应信息"

10、@ApiIgnore():用于类或者方法上,不被显示在页面上

使用

实体类

代码语言:javascript
复制
@ApiModel("用户对象模型")

public class User {

      @ApiModelProperty(value = "用户id",name = "id",required = true)
    private Long id;
    @ApiModelProperty(value = "用户名",name = "username",required = true)
    private String username;
    @ApiModelProperty(value = "密码",name = "password",required = true)

    private String password;
    @ApiModelProperty(value = "邮箱",name = "email",required = false)

    private String email;

get set方法}

controller(我们进行模拟,不连接数据库)

代码语言:javascript
复制
package com.zx.controller;

import com.zx.bean.User;
import io.swagger.annotations.*;
import net.bytebuddy.implementation.bind.annotation.Default;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import springfox.documentation.service.Tags;

/**
 * @Author CaesarChang张旭
 * @Date 2020/12/17  9:33 下午
 * @Version 1.0
 */
@RestController
@RequestMapping("/user")
@Api(tags={"用户管理api"})
public class UserController {

    @PostMapping
    @ApiOperation(value = "新增用户",notes = "新增返回新增的用户")
    @ApiResponses({
            @ApiResponse(code = 400,message = "id==1参数没填好"),
            @ApiResponse(code = 401,message = "id==2权限不足"),
            @ApiResponse(code = 200,message = "新增成功")
    })
    public ResponseEntity<User> add(User user) {

        if (user.getId() == 1) {
            return new ResponseEntity<>(user, HttpStatus.BAD_REQUEST);  //400
        } else if (user.getId() == 2) {
            return new ResponseEntity<>(user, HttpStatus.UNAUTHORIZED); //401
        }else{
            return new ResponseEntity<>(user, HttpStatus.OK);//200
        }
    }

    @PutMapping
    @ApiIgnore
    public ResponseEntity<User> update(User user) {

        if (user.getId() == 1) {
            return new ResponseEntity<>(user, HttpStatus.BAD_REQUEST);  //400
        } else if (user.getId() == 2) {
            return new ResponseEntity<>(user, HttpStatus.UNAUTHORIZED); //401
        }else{
            return new ResponseEntity<>(user, HttpStatus.OK);//200
        }
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除用户",notes = "删除返回删除id")
    @ApiResponses({
            @ApiResponse(code = 400,message = "id==1参数没填好"),
            @ApiResponse(code = 401,message = "id==2权限不足"),
            @ApiResponse(code = 200,message = "删除成功")
    })
    public ResponseEntity<Long> delete(Long id) {

        if (id == 1) {
            return new ResponseEntity<>(id, HttpStatus.BAD_REQUEST);  //400
        } else if (id == 2) {
            return new ResponseEntity<>(id, HttpStatus.UNAUTHORIZED); //401
        }else{
            return new ResponseEntity<>(id, HttpStatus.OK);//200
        }
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询",notes="通过id查询")
    @ApiImplicitParam(paramType = "path",name = "id",value = "要查询的id",readOnly = true)
    public ResponseEntity<Long> get(@PathVariable("id") Long id) {

        if (id == 1) {
            return new ResponseEntity<>(id, HttpStatus.BAD_REQUEST);  //400
        } else if (id == 2) {
            return new ResponseEntity<>(id, HttpStatus.UNAUTHORIZED); //401
        }else{
            return new ResponseEntity<>(id, HttpStatus.OK);//200
        }
    }


    @PostMapping("/list-page")
    @ApiOperation(value = "分页查询",notes="得到分页查询对象")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query",name = "pageNum",value = "页码",required = false),
            @ApiImplicitParam(paramType = "query",name = "pageSize",value="每页行数",required = false)

    })
    public ResponseEntity<String> getList(@RequestParam(defaultValue = "1",required = false) Integer pageNum, @RequestParam(defaultValue = "1",required = false)Integer pageSize) {
        return ResponseEntity.ok("分页成功");
    }

}

结果

使用swagger测试文件上传

拜了个拜!么么哒!

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/12/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1简介
  • 2配置swagger
  • 3常用注解
相关产品与服务
项目管理
CODING 项目管理(CODING Project Management,CODING-PM)工具包含迭代管理、需求管理、任务管理、缺陷管理、文件/wiki 等功能,适用于研发团队进行项目管理或敏捷开发实践。结合敏捷研发理念,帮助您对产品进行迭代规划,让每个迭代中的需求、任务、缺陷无障碍沟通流转, 让项目开发过程风险可控,达到可持续性快速迭代。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档