Swagger是什么?
Swagger官方文档
个人理解:Swagger 就是为了实现前后端分离而生成的一个API管理工具。
Swagger自动的将后端的所有接口都整合起来,并且有详细的接口信息给前端人员进行使用。而前端人员无需管底层接口,直接在Swagger上就能够进行相应的测试。没问题后再发布。这就是Swagger的核心作用!
Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web
服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。
如何使用
第一步:导入相关依赖
<!-- springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
第二步:进行Swagger配置
新建SwaggerConfig.java
/**
* Copyright (C), Lucius
* FileName: SwaggerConfig
* Author:
* Date: 2020/4/13 17:44
* Description:
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.lucius.swagger.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2//开启swagger
public class SwaggerConfig {
//通过配置文件来读取flag,适合多环境时使用
@Value("${Swagger.enableFlag}")
private Boolean flag;
//配置swagger的Docker的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("Lucius")
.apiInfo(apiInfo())
//配置是否运行swagger-ui,默认true
.enable(flag)
.select()
//指定需要扫描
.apis(RequestHandlerSelectors.basePackage("com.lucius.swagger.controller"))
//过滤不需要扫描地址
//.paths(PathSelectors.ant("/lucius/**"))
.build();
}
/*
多人协同的时候可以设置多个组
可以仿照上面这种扫描相应的类
*/
@Bean
public Docket docketA(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");}
@Bean
public Docket docketB(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");}
//配置swagger信息 apiInfo
//就是你访问swagger-ui.html这个网页显示的信息
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("Lucius","https://github.com/Lucius888","");
return new ApiInfo(
"Lucius的Seagger API文档",
"为了生活",
"v1.0",
"https://github.com/Lucius888",
contact,
"Apache 2.0",
"https://github.com/Lucius888",
new ArrayList()
);
}
}
代码解释: 从上到下
- 想要使用Swagger,肯定是需要
@EnableSwagger2
//开启swagger - 配置中最重要的就是配置swagger的
Docker
的bean实例,里面有很多参数,其中最重要的就是enable
和apis(RequestHandlerSelectors.basePackage("com.lucius.swagger.controller"))
一个设置Swagger-ui能否应用(开发就true,上线产品就false),一个设置能够扫描到的包(该包下的所有接口都将被扫描) - 然后就是
ApiInfo
设置你Swagger-ui界面的基本信息,装逼用的。
第三步:写个实体和controller
首先对一些注解进行说明:
API注解
@Api
用在类上,该注解将一个Controller(Class)标注为一个swagger资源(API)。在默认情况下,Swagger-Core只会扫描解析具有@Api注解的类,而会自动忽略其他类别资源(JAX-RS endpoints,Servlets等等)的注解。该注解包含以下几个重要属性
- tags
API分组标签。具有相同标签的API将会被归并在一组内展示。 - value
如果tags没有定义,value将作为Api的tags使用 - description
API的详细描述,在1.5.X版本之后不再使用,但实际发现在2.0.0版本中仍然可以使用
@ApiOperation
在指定的(路由)路径上,对一个操作或HTTP方法进行描述。具有相同路径的不同操作会被归组为同一个操作对象。不同的HTTP请求方法及路径组合构成一个唯一操作。此注解的属性有:
- value
对操作的简单说明,长度为120个字母,60个汉字。 - notes
对操作的详细说明。 - httpMethod
HTTP请求的动作名,可选值有:“GET”, “HEAD”, “POST”, “PUT”, “DELETE”, “OPTIONS” and “PATCH”。 - code
默认为200,有效值必须符合标准的HTTP Status Code Definitions。
@ApiImplicitParams
用在方法上,注解ApiImplicitParam的容器类,以数组方式存储。
@ApiImplicitParam
对API的单一参数进行注解。虽然注解@ApiParam同JAX-RS参数相绑定,但这个@ApiImplicitParam注解可以以统一的方式定义参数列表,也是在Servelet及非JAX-RS环境下,唯一的方式参数定义方式。注意这个注解@ApiImplicitParam必须被包含在注解@ApiImplicitParams之内。可以设置以下重要参数属性:
- name
参数名称 - value
参数的简短描述 - required
是否为必传参数 - dataType
参数类型,可以为类名,也可以为基本类型(String,int、boolean等) - paramType
参数的传入(请求)类型,可选的值有path, query, body, header or form。
@ApiParam
增加对参数的元信息说明。这个注解只能被使用在JAX-RS 1.x/2.x的综合环境下。其主要的属性有
- required
是否为必传参数,默认为false - value
参数简短说明
@ApiResponses
注解@ApiResponse的包装类,数组结构。即使需要使用一个@ApiResponse注解,也需要将@ApiResponse注解包含在注解@ApiResponses内。
@ApiResponse
描述一个操作可能的返回结果。当REST API请求发生时,这个注解可用于描述所有可能的成功与错误码。可以用,也可以不用这个注解去描述操作的返回类型,但成功操作的返回类型必须在@ApiOperation中定义。如果API具有不同的返回类型,那么需要分别定义返回值,并将返回类型进行关联。但Swagger不支持同一返回码,多种返回类型的注解。注意:这个注解必须被包含在@ApiResponses注解中。
- code
HTTP请求返回码。有效值必须符合标准的HTTP Status Code Definitions。 - message
更加易于理解的文本消息 - response
返回类型信息,必须使用完全限定类名,比如“com.xyz.cc.Person.class”。
responseContainer
如果返回类型为容器类型,可以设置相应的值。有效值为 “List”, “Set” or “Map”,其他任何无效的值都会被忽略。
Model注解
对于Model的注解,Swagger提供了两个:@ApiModel及@ApiModelProperty,分别用以描述Model及Model内的属性。
@ApiModel
描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
提供对Swagger model额外信息的描述。在标注@ApiOperation注解的操作内,所有的类将自动被内省(introspected),但利用这个注解可以做一些更加详细的model结构说明。主要属性有:
- value
- model的别名,默认为类名
- description,model的详细描述
@ApiModelProperty
描述一个model的属性
对model属性的注解,主要的属性值有:
- value
属性简短描述 - example
属性的示例值 - required
是否为必须值
实体类:
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="BizComponent对象", description="组件")
public class BizComponent implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty(value = "分类")
private Long categoryId;
@ApiModelProperty(value = "组件名称")
private String name;
@ApiModelProperty(value = "组件描述")
private String description;
@ApiModelProperty(value = "日期字段")
private LocalDateTime componentTime;
@ApiModelProperty(value = "创建时间")
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@ApiModelProperty(value = "修改时间")
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime modifiedTime;
}
controller:
@AllArgsConstructor
@RestController
@RequestMapping("/api/category")
@Api(value = "/category", tags = "组件分类")
public class BizCategoryController {
private IBizCategoryService bizCategoryService;
@GetMapping("/list")
@ApiOperation(value = "列表", notes = "分页列表")
public R<PageModel<BizCategory>> list(PageQuery pageQuery,
@RequestParam @ApiParam("组件分类名称") String name) {
IPage<BizCategory> page = bizCategoryService.page(pageQuery.loadPage(),
new LambdaQueryWrapper<BizCategory>().like(BizCategory::getName, name));
return R.success(page);
}
@GetMapping("/list/all")
@ApiOperation(value = "查询所有", notes = "分页列表")
public R<List<BizCategory>> listAll() {
List<BizCategory> categories = bizCategoryService.list();
return R.success(categories);
}
@GetMapping("/{categoryId}")
@ApiOperation(value = "详情", notes = "组件分类详情")
public R<BizCategory> detail(@PathVariable @ApiParam("分类Id") Long categoryId) {
BizCategory category = bizCategoryService.getById(categoryId);
return R.success(category);
}
@PostMapping("/save")
@ApiOperation(value = "保存", notes = "新增或修改")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "form", name = "categoryId", value = "组件id(修改时为必填)"),
@ApiImplicitParam(paramType = "form", name = "name", value = "组件分类名称", required = true)
})
public R<BizCategory> save(Long categoryId, String name) {
BizCategory category = new BizCategory();
category.setId(categoryId);
category.setName(name);
bizCategoryService.saveOrUpdate(category);
return R.success(category);
}
@DeleteMapping("/{categoryId}")
@ApiOperation(value = "删除", notes = "删除")
public R delete(@PathVariable @ApiParam("分类Id") Long categoryId) {
bizCategoryService.delete(categoryId);
return R.success();
}
}
效果图