1. 什么是Swagger?
Swagger™的目标是为REST APIs 定义一个标准的,与语言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下能发现和理解各种服务的功能。当服务通过Swagger定义,消费者就能与远程的服务互动通过少量的实现逻辑。类似于低级编程接口,Swagger去掉了调用服务时的很多猜测。
浏览 Swagger 去了解更多关于Swagger 项目的信息,包括附加的支持其他语言的库。
2. 在项目中集成Swagger
-
2.1 引入maven依赖
我自己的项目中使用的是swagger2。
org.springframework.boot spring-boot-starter-parent 2.2.2.RELEASE org.springframework.boot spring-boot-starter-web 2.2.2.RELEASE io.springfox springfox-swagger-ui 2.9.2 io.springfox springfox-swagger2 2.9.2 org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.0 mysql mysql-connector-java 8.0.18 org.projectlombok lombok 1.18.10 org.springframework.boot spring-boot-maven-plugin org.apache.maven.plugins maven-compiler-plugin -parameters -
2.2 Swagger的配置
SwggerConfig.java
:package com.butterflytri.config; import com.google.common.base.Predicates; import io.swagger.annotations.ApiOperation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.ParameterBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.schema.ModelRef; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.service.Parameter; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author: WJF * @date: 2020/5/21 * @description: SwaggerConfig */ /** * {@link Configuration}:标志这是一个配置类,在spring boot引导类启动时,会自动加载这个类的配置。 * {@link Profile}:说明加载配置文件 'application.yml' 时加载对应的配置。 * {@link EnableSwagger2}:启用Swagger2的配置。 */ @Configuration @Profile("dev") @EnableSwagger2 public class SwaggerConfig { @Bean public Docket restApi() { Class[] classes = this.getClasses(); Set
consumesSet = new HashSet<>(); consumesSet.add("application/x-www-form-urlencoded"); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .globalOperationParameters(parameters()) .ignoredParameterTypes(classes) .forCodeGeneration(true) .consumes(consumesSet) .select() .apis(Predicates.and(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))) .paths(PathSelectors.any()) .build(); } /** * API文档的基本信息 * @return ApiInfo */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("学生管理平台") .description("学生管理平台文档") .termsOfServiceUrl("http://127.0.0.1:8080/butterflytri/swagger-ui.html") .contact(new Contact("wjf", "http://butterflytri.com", "[email protected]")) .version("2.0") .build(); } /** * Swagger2可以在Swagger2文档中添加参数 * @return List */ private List parameters() { // 添加一个参数butterflytri,参数描述:不死蝶 ParameterBuilder paramBuilder = new ParameterBuilder(); List paramList = new ArrayList (); paramBuilder.name("butterflytri") .description("不死蝶") .modelRef(new ModelRef("string")) .parameterType("header") .required(true) .build(); paramList.add(paramBuilder.build()); return paramList; } /** * 获取class数组 * @return Class[] */ private Class[] getClasses() { return new Class[]{}; } } -
2.3 控制层
StudentController.java
:package com.butterflytri.controller; import com.butterflytri.entity.Student; import com.butterflytri.service.StudentService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; /** * @author: WJF * @date: 2020/5/16 * @description: StudentController */ @Api(tags = "学生管理接口") @RestController @RequestMapping("/student") public class StudentController { @Resource private StudentService studentService; /** * GET :请求从服务器获取特定资源。举个例子:GET /student(获取所有学生) * @return List
*/ @ApiOperation(value = "查询所有学生", httpMethod = "GET", notes = "查询所有学生") @GetMapping("/student") public List student() { return studentService.findAll(); } /** * GET :请求从服务器获取特定资源。举个例子:GET /student/1(获取id为1学生) * @param id * @return Student */ @ApiOperation(value = "查询学生详情", httpMethod = "GET", notes = "查询学生详情") @ApiImplicitParam(name = "id", value = "学生id", required = true, paramType = "form", dataTypeClass = Long.class) @GetMapping("/student/{id}") public Student student(@PathVariable("id") Long id) { return studentService.findOne(id); } /** * POST :在服务器上创建一个新的资源。举个例子:POST /student(添加学生) * @param student */ @PostMapping("/student") @ApiOperation(value = "添加学生", httpMethod = "POST", notes = "添加学生") @ApiImplicitParams({ @ApiImplicitParam(name = "studentName", value = "学生姓名", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "studentNo", value = "学生学号", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "sex", value = "学生性别", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "age", value = "学生年龄", required = true, paramType = "form", dataTypeClass = Integer.class) }) public void student(@RequestBody Student student) { studentService.add(student); } /** * PUT :更新服务器上的资源(客户端提供更新后的整个资源)。举个例子:PUT /student/1(更新学号为 1 的学生的所有信息) * @param id */ @PutMapping("/student/{id}") @ApiOperation(value = "根据id修改学生信息(大范围)", httpMethod = "PUT", notes = "根据id修改学生信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "学生id", required = true, paramType = "from", dataTypeClass = Long.class), @ApiImplicitParam(name = "studentName", value = "学生姓名", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "studentNo", value = "学生学号", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "sex", value = "学生性别", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "age", value = "学生年龄", required = true, paramType = "form", dataTypeClass = Integer.class) }) public void updateById(@PathVariable("id") Long id, Student student) { studentService.updateAll(id,student); } /** * DELETE :从服务器删除特定的资源。举个例子:DELETE /student/1(删除学号为 1 的学生) * @param id */ @DeleteMapping("/student/{id}") @ApiOperation(value = "根据id删除学生信息", httpMethod = "DELETE", notes = "根据id删除学生信息") @ApiImplicitParam(name = "id", value = "学生id", required = true, paramType = "from", dataTypeClass = Long.class) public void deleteById(@PathVariable("id") Long id) { studentService.delete(id); } /** * PATCH :更新服务器上的资源(客户端提供更改的属性,可以看做作是部分更新),使用的比较少,这里就不举例子了。 * @param id * @param student */ @PatchMapping("/student/{id}") @ApiOperation(value = "根据id修改学生信息(小范围)", httpMethod = "PATCH", notes = "根据id修改学生信息") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "学生id", required = true, paramType = "from", dataTypeClass = Long.class), @ApiImplicitParam(name = "studentName", value = "学生姓名", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "studentNo", value = "学生学号", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "sex", value = "学生性别", required = true, paramType = "form", dataTypeClass = String.class), @ApiImplicitParam(name = "age", value = "学生年龄", required = true, paramType = "form", dataTypeClass = Integer.class) }) public void updatePart(@PathVariable("id") Long id, Student student) { studentService.updatePart(id,student); } } 这些注解也是很容易理解的,相信各位聪明的技术大牛很快就会使用了。这些注解的具体作用其实看看就懂了,甚至不用去查资料,在这里解释下
@ApiImplicitParam
这个注解的一个属性paramType
,这个属性的取值有以下几种:- header:放在请求头,用于请求头参数的获取。使用
@RequestHeader
,在代码中接收参数。 - query:用于get请求的参数拼接。使用
@RequestParam
,在代码中接收参数。 - path:用于restful接口请求参数的获取。使用
@PathVariable
,在映射地址上接收参数。 - body:放在请求体中,使用
@RequestBody
接收参数。 - form:使用form表单的形式传递参数。
- header:放在请求头,用于请求头参数的获取。使用
-
2.4 Entity
Student.java
:package com.butterflytri.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.io.Serializable; /** * @author: WJF * @date: 2020/5/16 * @description: Student */ @ToString @Getter @Setter @ApiModel("学生Entity") public class Student implements Serializable { @ApiModelProperty("学生id") private Long id; @ApiModelProperty("学生姓名") private String studentName; @ApiModelProperty("学生学号") private String studentNo; @ApiModelProperty("性别") private String sex; @ApiModelProperty("年龄") private Integer age; }
可以使用
@ApiModelProperty
注解来标识每个Entity属性的意思。 -
2.5 运行结果
启动项目,访问
http://127.0.0.1:8080/butterflytri/swagger-ui.html
即可看到下面的页面:点开学生管理接口可以看到
StudentController.java
中写的所有接口方法:点开下面的Models,可以看到Entity中的
Student.java
实体类:再点开查询所有学生这个方法,调用一下这个方法,点击Try it out测试一下方法:
在这里看到了一个参数
butterflytri
,而且还是必传参数,这是因为我在SwaggerConfig.java
这个配置文件类中进行了配置,不清楚的可以往上翻一翻,看看那个配置类。点击了Try it out按钮后,随便给这个参数赋值,反正这个参数没有什么,只是给大家做演示看的。然后点击execute按钮,就可以看到返回结果:
3. 项目地址
本项目传送门:
- GitHub ---> spring-boot-swagger-ui
- Gitee ---> spring-boot-swagger-ui
此教程会一直更新下去,觉得博主写的可以的话,关注一下,也可以更方便下次来学习。
- 作者:Butterfly-Tri
- 出处:Butterfly-Tri个人博客
- 版权所有,欢迎保留原文链接进行转载