Spring Boot 教程 (4) - swagger-ui
1. 什么是Swagger?
Swagger™的目标是为REST APIs 定义一个标准的,与语言无关的接口,使人和计算机在看不到源码或者看不到文档或者不能通过网络流量检测的情况下能发现和理解各种服务的功能。当服务通过Swagger定义,消费者就能与远程的服务互动通过少量的实现逻辑。类似于低级编程接口,Swagger去掉了调用服务时的很多猜测。
浏览 Swagger 去了解更多关于Swagger 项目的信息,包括附加的支持其他语言的库。
2. 在项目中集成Swagger
2.1 引入maven依赖
我自己的项目中使用的是swagger2。
<!--springboot父工程-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <dependencies>
<!--springboot框架web组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<!--swagger-ui组件-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger组件-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--mybatis整合springboot组件-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--mysql数据库连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<!--lombok组件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies> <build>
<!--springboot的maven插件-->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
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<String> 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", "butterflytri@163.com"))
.version("2.0")
.build();
} /**
* Swagger2可以在Swagger2文档中添加参数
* @return List<Parameter>
*/
private List<Parameter> parameters() {
// 添加一个参数butterflytri,参数描述:不死蝶
ParameterBuilder paramBuilder = new ParameterBuilder();
List<Parameter> paramList = new ArrayList<Parameter>();
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<Student>
*/
@ApiOperation(value = "查询所有学生", httpMethod = "GET", notes = "查询所有学生")
@GetMapping("/student")
public List<Student> 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. 项目地址
本项目传送门:spring-boot-swagger-ui
此教程会一直更新下去,觉得博主写的可以的话,关注一下,也可以更方便下次来学习。
Spring Boot 教程 (4) - swagger-ui的更多相关文章
- 【Spring Boot&&Spring Cloud系列】Spring Boot项目集成Swagger UI
前言 Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器以同样的速度来更新.文件的方法,参数和模型紧密集 ...
- 程序员DD 《Spring boot教程系列》补充
最近在跟着程序员DD的Spring boot教程系列学习Spring boot,由于年代原因,Spring boot已经发生了一些变化,所以在这里进行一些补充. 补充的知识大多来自评论区,百度,Sta ...
- Spring Boot:整合Swagger文档
综合概述 spring-boot作为当前最为流行的Java web开发脚手架,越来越多的开发者选择用其来构建企业级的RESTFul API接口.这些接口不但会服务于传统的web端(b/s),也会服务于 ...
- Spring Boot 教程
Spring Boot 系列教程: Spring Boot:快速入门教程 Spring Boot:整合Swagger文档 Spring Boot:整合MyBatis框架 Spring Boot:实现M ...
- Spring Boot中使用Swagger CodeGen生成REST client
文章目录 什么是Open API规范定义文件呢? 生成Rest Client 在Spring Boot中使用 API Client 配置 使用Maven plugin 在线生成API Spring B ...
- Spring Boot教程(十六)属性配置文件详解(1)
相信很多人选择Spring Boot主要是考虑到它既能兼顾Spring的强大功能,还能实现快速开发的便捷.我们在Spring Boot使用过程中,最直观的感受就是没有了原来自己整合Spring应用时繁 ...
- Spring Boot 快速整合Swagger
一.前言 Spring Boot作为当前最为流行的Java web开发脚手架,越来越多的开发者选择用其来构建企业级的RESTFul API接口.这些接口不但会服务于传统的web端(b/s),也会服务于 ...
- Spring Boot教程(二十二)使用Swagger2构建强大的RESTful API文档(1)
由于Spring Boot能够快速开发.便捷部署等特性,相信有很大一部分Spring Boot的用户会用来构建RESTful API.而我们构建RESTful API的目的通常都是由于多终端的原因,这 ...
- 1024|推荐一个开源免费的Spring Boot教程
2020-1024=996! 今天,星期六,你们是否加班了?我反正加了!早上去公司开了一早上会,中午回家写下了这篇文章. 今天,我要推荐一个开源免费的Spring Boot项目,就是我最近日更的Spr ...
随机推荐
- 【Linux常见命令】tar命令
[独立命令,只能用其中一个,和别的命令连用]这五个是独立的命令,压缩解压都要用到其中一个,可以和别的命令连用但只能用其中一个. -c: 建立压缩档案 -x:解压 -t:查看内容 -r:向压缩归档文件末 ...
- IBM:向所有云平台开放Watson人工智能系统
据美国科技媒体TechCrunch报道,IBM今天宣布不再把沃森(Watson)品牌的人工智能服务局限于自家云计算服务,而是会允许其他企业在自己的数据中心里使用和运行这个平台."客户很难把人 ...
- Netflix:当你按下“播放”的时候发生了什么?
从用户端来看,使用Netflix是很简单的,按下播放键之后视频就像变魔术一样完美呈现了.看起来很容易是吧?然而实际不是这样的.了解过云计算的人可能会简单地以为,既然Netflix使用AWS来提供视频服 ...
- Socket中SO_REUSEADDR简介
SO_REUSEADDR:字面意思重复使用地址 一般来说,一个端口释放后会等待两分钟之后才能再次被使用,SO_REUSEADDR是让端口释放后立即就可以被再次使用. SO_REUSEADDR用于对TC ...
- 请不要浪费你的生命,一文多发推广就用它(OpenWrite)
你我的共同困惑 你是否跟我一样?刚开始尝试写作,自己没有名气,有以下几个困惑: 想要推广自己,想在多个平台发文? 多平台发文之后,想要看各个平台的流量如何? 有了流量,想要引流用户到自己的网站? 网站 ...
- VUE简单整理
在用 Vue.js 构建大型应用时推荐使用 NPM 安装: # 最新稳定版 $ cnpm install vue 命令行工具 Vue.js 提供一个官方命令行工具,可用于快速搭建大型单页应用. # 全 ...
- 再谈 PHP 未来之路
前段时间我写过一篇博文<phper:敢问路在何方>,分析了 PHPer 的困境以及 PHP 程序员的学习.进阶突破之路.同时我在知乎上也发过类似的提问.从大家的评论和回答看,大体分为以下几 ...
- Java——Java连接Jira,创建、修改、删除工单信息
还不了解Jira是什么的同学可以看一下这篇文章:https://www.cnblogs.com/wgblog-code/p/11750767.html 本篇文章主要介绍如何使用Java操作Jira,包 ...
- Spring Cloud Alibaba系列(一)nacos作为服务注册中心
Spring Cloud Alibaba各组件版本关系 Spring Cloud Alibaba Version Sentinel Version Nacos Version RocketMQ Ver ...
- php报错:strip_tags() expects parameter 1 to be string, array given
囧....... 这个表示参数需要字符串,而你传入了数组,所以出错了~ 检查下函数或者方法是否正确,还有参数