SpringBoot——Swagger2 接口规范

优质博文:IT-BLOG-CN

如今,REST和微服务已经有了很大的发展势头。但是,REST规范中并没有提供一种规范来编写我们的对外REST接口API文档。每个人都在用自己的方式记录api文档,因此没有一种标准规范能够让我们很容易的理解和使用该接口。我们需要一个共同的规范和统一的工具来解决文档的难易理解文档的混乱格式。Swagger(在谷歌、IBM、微软等公司的支持下)做了一个公共的文档风格来填补上述问题。在本博客中,我们将会学习怎么使用SwaggerSwagger2注解去生成REST API文档。

Swagger(现在是“开放 API计划”)是一种规范和框架,它使用一种人人都能理解的通用语言来描述REST API。还有其他一些可用的框架,比如RAML、求和等等,但是 Swagger是最受欢迎的。它提供了人类可读和机器可读的文档格式。它提供了JSONUI支持。JSON可以用作机器可读的格式,而 Swagger-UI是用于可视化的,通过浏览api文档,人们很容易理解它。

一、添加 Swagger2 的 maven依赖

打开项目中的 pom.xml文件,添加以下两个 swagger依赖。springfox-swagger2 、springfox-swagger-ui。

<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.6.1</version>
</dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.6.1</version>
</dependency>

实际上,Swagger的 API有两种类型,并在不同的工件中维护。今天我们将使用 springfox,因为这个版本可以很好地适应任何基于 spring的配置。我们还可以很容易地尝试其他配置,这应该提供相同的功能——配置中没有任何变化。

二、添加 Swagger2配置

使用 Java config的方式添加配置。为了帮助你理解这个配置,我在代码中写了相关的注释:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.google.common.base.Predicates;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class Swagger2UiConfiguration extends WebMvcConfigurerAdapter
{@Beanpublic Docket api() {// @formatter:off//将控制器注册到 swagger//还配置了Swagger 容器return new Docket(DocumentationType.SWAGGER_2).select().apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any())//扫描 controller所有包.apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot"))).paths(PathSelectors.any()).paths(PathSelectors.ant("/swagger2-demo")).build();// @formatter:on}@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry){//为可视化文档启用swagger ui部件registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");}
}

通过 api()方法返回 Docket,调用以下方法:
【1】apiInfo()方法中可以添加 api文档的基本信息(具体类型查看文档);
【2】select()方法返回 ApiSelectorBuilder实例,用于过滤哪些 api需要显示;
【3】apis()方法中填写项目中 Controller类存放的路径;

最后 build()建立 Docket。

三、验证 Swagger2的 JSON格式文档

在application.yml中配置服务名为:swagger2-demo

server.contextPath=/swagger2-demo

maven构建并启动服务器。打开链接,会生成一个JSON格式的文档。这并不是那么容易理解,实际上Swagger已经提供该文档在其他第三方工具中使用,例如当今流行的 API管理工具,它提供了API网关、API缓存、API文档等功能。

四、验证 Swagger2 UI文档

打开链接 在浏览器中来查看Swagger UI文档;

五、Swagger2 注解的使用

默认生成的 API文档很好,但是它们缺乏详细的 API级别信息。Swagger提供了一些注释,可以将这些详细信息添加到 api中。如。@Api我们可以添加这个注解在 Controller上,去添加一个基本的 Controller说明。

@Api(value = "Swagger2DemoRestController", description = "REST APIs related to Student Entity!!!!")
@RestController
public class Swagger2DemoRestController {//...
}

@ApiOperation and @ApiResponses我们添加这个注解到任何 Controller的 rest方法上来给方法添加基本的描述。例如:

@ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Success|OK"),@ApiResponse(code = 401, message = "not authorized!"),@ApiResponse(code = 403, message = "forbidden!!!"),@ApiResponse(code = 404, message = "not found!!!") })@RequestMapping(value = "/getStudents")
public List<Student> getStudents() {return students;
}

在这里,我们可以向方法中添加标签,来在 swagger-ui中添加一些分组。@ApiModelProperty这个注解用来在数据模型对象中的属性上添加一些描述,会在 Swagger UI中展示模型的属性。例如:

@ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")
private String name;

Controller 和 Model 类添加了swagger2注解之后,代码清单:Swagger2DemoRestController.java

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springbootswagger2.model.Student;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;@Api(value = "Swagger2DemoRestController", description = "REST Apis related to Student Entity!!!!")
@RestController
public class Swagger2DemoRestController {List<Student> students = new ArrayList<Student>();{students.add(new Student("Sajal", "IV", "India"));students.add(new Student("Lokesh", "V", "India"));students.add(new Student("Kajal", "III", "USA"));students.add(new Student("Sukesh", "VI", "USA"));}@ApiOperation(value = "Get list of Students in the System ", response = Iterable.class, tags = "getStudents")@ApiResponses(value = {@ApiResponse(code = 200, message = "Suceess|OK"),@ApiResponse(code = 401, message = "not authorized!"),@ApiResponse(code = 403, message = "forbidden!!!"),@ApiResponse(code = 404, message = "not found!!!") })@RequestMapping(value = "/getStudents")public List<Student> getStudents() {return students;}@ApiOperation(value = "Get specific Student in the System ", response = Student.class, tags = "getStudent")@RequestMapping(value = "/getStudent/{name}")public Student getStudent(@PathVariable(value = "name") String name) {return students.stream().filter(x -> x.getName().equalsIgnoreCase(name)).collect(Collectors.toList()).get(0);}@ApiOperation(value = "Get specific Student By Country in the System ", response = Student.class, tags = "getStudentByCountry")@RequestMapping(value = "/getStudentByCountry/{country}")public List<Student> getStudentByCountry(@PathVariable(value = "country") String country) {System.out.println("Searching Student in country : " + country);List<Student> studentsByCountry = students.stream().filter(x -> x.getCountry().equalsIgnoreCase(country)).collect(Collectors.toList());System.out.println(studentsByCountry);return studentsByCountry;}// @ApiOperation(value = "Get specific Student By Class in the System ",response = Student.class,tags="getStudentByClass")@RequestMapping(value = "/getStudentByClass/{cls}")public List<Student> getStudentByClass(@PathVariable(value = "cls") String cls) {return students.stream().filter(x -> x.getCls().equalsIgnoreCase(cls)).collect(Collectors.toList());}
}

Student.java 实体类

import io.swagger.annotations.ApiModelProperty;public class Student
{@ApiModelProperty(notes = "Name of the Student",name="name",required=true,value="test name")private String name;@ApiModelProperty(notes = "Class of the Student",name="cls",required=true,value="test class")private String cls;@ApiModelProperty(notes = "Country of the Student",name="country",required=true,value="test country")private String country;public Student(String name, String cls, String country) {super();this.name = name;this.cls = cls;this.country = country;}public String getName() {return name;}public String getCls() {return cls;}public String getCountry() {return country;}@Overridepublic String toString() {return "Student [name=" + name + ", cls=" + cls + ", country=" + country + "]";}
}

六、swagger-ui 展示

现在,当我们的 REST api得到适当的注释时,让我们看看最终的输出。打开http://localhost:8080/swagger2-demo/swagger-ui。在浏览器中查看 Swagger ui文档。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/182514.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

传感器:探索Android中的传感器功能与使用

传感器&#xff1a;探索Android中的传感器功能与使用 一、传感器介绍1.1 Android 平台三大类传感器1.2 Android 平台支持的传感器1.3 传感器框架 二、传感器的使用2.1 识别传感器和传感器特性2.2 针对不同制造商的传感器或传感器的不同版本优化2.3 监控传感器事件2.4 处理不同的…

OpenCV | 图像梯度sobel算子、scharr算子、lapkacian算子

import cv2 #opencv读取的格式是BGR import numpy as np import matplotlib.pyplot as plt#Matplotlib是RGB %matplotlib inline 1、sobel算子 img cv2.imread(pie.png,cv2.IMREAD_GRAYSCALE) cv2.imshow(img,img) cv2.waitKey() cv2.destroyAllWindows() pie图片 dst cv2.S…

vue3+vite搭建cesium项目

1.创建项目 cnpm create vite 2.安装依赖 npm i cesium vite-plugin-cesium vite -D 3.在vite.config.js里进行配置 import { defineConfig } from vite import vue from vitejs/plugin-vue import cesium from vite-plugin-cesium; export default defineConfig({plugins…

NCo3.1(08) - Nco3 服务器端编程

本篇博文不再重复ABAP调用外部服务器的基础&#xff0c;只介绍 NCo3 开发的过程和要点。需要了解相关知识点的小伙伴们自行参考&#xff1a; SAP接口编程 之JCo3.0系列(06) - Jco服务器端编程 PyRFC 服务器端编程要点 创建项目 新建一个 Console 项目&#xff0c;选择 .Net …

失落的艺术:无着色器3D渲染

假设你想创建一个甜蜜的弹跳立方体&#xff0c;如下所示&#xff1a; 一个弹跳的立方体 你可以使用 3D 框架&#xff0c;例如 OpenGL 或 Metal。 这涉及编写一个或多个顶点着色器来变换 3D 对象&#xff0c;以及编写一个或多个片段着色器来在屏幕上绘制这些变换后的对象。 然…

Python中对数组连续赋值的问题

问题描述 在python中&#xff0c;首先用两个等号对两个数组进行初始化并赋值。之后&#xff0c;对任何一个数组进行赋值&#xff0c;都会将其赋予相同值。 import numpy as np Array1 Array2 np.empty(2) Array1[0],Array2[0]70,80 print(Array1[0],Array2[0])80.0 80.0 …

旋转的数组

分享今天看到的一个题目&#xff0c;不同思路解法 题目 思路1&#xff1a;时间复杂度0(N*k&#xff09; void rotate(int *a,int N,int k)//N为数组元素个数 { while(k--) { int tema[N-1]; for(int rightN-2;right>0;right--) { a[right1]a[right]; } a[0]tem; …

聊聊VMware vSphere

VMware vSphere是一种虚拟化平台和云计算基础设施解决方案&#xff0c;由VMware公司开发。它为企业提供了一种强大的虚拟化和云计算管理平台&#xff0c;能够在数据中心中运行、管理和保护应用程序和数据。vSphere平台与VMware ESXi虚拟化操作系统相结合&#xff0c;提供了完整…

水果编曲软件FL Studio21最新中文版本2023年最新FL 21中文版如何快速入门教程

水果编曲软件FL Studio介绍 各位&#xff0c;大家晚上好&#xff0c;今天给大家带来最新最新2023水果编曲软件FL Studio 21中文版下载安装激活图文教程。我们一起先了解一些FL Studio 。FL Studio21是目前流行广泛使用人数最多音乐编曲宿主制作DAW软件&#xff0c;这款软件相信…

java开发需要用到的软件,必备软件工具一览

java开发需要用到的软件&#xff0c;必备软件工具一览 如果你对Java编程感兴趣或已经是一名Java开发者&#xff0c;你需要一些必备的软件工具来提高你的生产力和简化开发过程。在本文中&#xff0c;我们将探讨Java开发所需的关键软件工具&#xff0c;并通过具体示例来解释它们的…

最新消息:滴滴 P0 事故原因,原因出来了

最新消息滴滴P0故障原因&#xff0c;是由于k8s集群升级导致的&#xff0c;后面又进行版本回退&#xff0c;由于现在大型互联网公司基本都是基于K8s进行部署的&#xff0c;如果K8s集群一出问题&#xff0c;上面运行的业务Pod和运维系统全部都得宕机&#xff0c;导致没法回滚。 …

二叉树(判断是否为单值二叉树)

题目&#xff08;力扣&#xff09;&#xff1a; 判断二叉树上每个节点的值是否相同&#xff0c;就需要让root节点分别与左节点和右节点分别比较是否相同。 注意&#xff1a;root等于空时&#xff0c;直接可以返回true&#xff1b; 首先&#xff0c;先判断他的特殊情况&#x…

如何在安防视频监控平台EasyCVR首页增添统计设备每个小时的温度展示功能?细节如下

安防视频监控/视频集中存储/云存储/磁盘阵列EasyCVR平台可拓展性强、视频能力灵活、部署轻快&#xff0c;可支持的主流标准协议有国标GB28181、RTSP/Onvif、RTMP等&#xff0c;以及支持厂家私有协议与SDK接入&#xff0c;包括海康Ehome、海大宇等设备的SDK等。平台既具备传统安…

BLIoTLink软网关,一键解决OT层与IT层的通信

在工业自动化领域&#xff0c;协议转换一直是一个重要的问题。不同的设备、系统往往使用不同的通信协议&#xff0c;这给数据采集、设备接入等带来很大的困扰。为了解决这个问题&#xff0c;各种协议转换软件应运而生。其中&#xff0c;BLIoTLink作为一款功能强大的嵌入式工业协…

常使用的定时任务

常使用的定时任务 一、 linux自带的定时任务 1、crontab 有这样一个需求&#xff1a;我们使用Java写一个工具jar包在系统空闲的时候去采集已经部署在Linux系统上的项目的一 些数据&#xff0c;可以使用 linux 系统的 crontab。 运行crontab -e&#xff0c;可以编辑定时器&…

[密码学]DES

先声明两个基本概念 代换&#xff08;substitution&#xff09;,用别的元素代替当前元素。des的s-box遵循这一设计。 abc-->def 置换&#xff08;permutation&#xff09;&#xff0c;只改变元素的排列顺序。des的p-box遵循这一设计。 abc-->bac DES最核心的算法就是…

使用nginx代理s3服务(私有云存储)

1、背景 公司网络安全原因&#xff0c;私有部署s3服务的机器无法被直接访问&#xff0c;所以需要加一层代理&#xff0c;通过访问代理去访问s3服务器&#xff0c;这里使用nginx进行代理。使用s3服务的方式是在代码中使用官方的java s3 sdk&#xff08;本文对于其他语言的官方s…

vue+jsonp编写可导出html的模版,可通过外部改json动态更新页面内容

效果 导出后文件结果如图所示&#xff0c;点击Index.html即可查看页面&#xff0c;页面所有数据由report.json控制&#xff0c;修改report.json内容即可改变index.html展示内容 具体实现 1. 编写数据存储的json文件 在index.html所在的public页面新建report.json文件&#xff…

彩虹云商城搭建教程+源码程序

前言&#xff1a;域名服务器或宝塔主机商场程序在线云商城 随着电子商务的快速发展&#xff0c;越来越多的企业开始意识到开设一个自己的电子商城对于销售和品牌推广的重要性。然而&#xff0c;选择一家合适的网站搭建平台和正确地构建一个商城网站并不是一件容易的事情。本文…

PyQt基础_008_ 按钮类控件QSpinbox

基本操作 import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import *class spindemo(QWidget):def __init__(self, parentNone):super(spindemo, self).__init__(parent)self.setWindowTitle("SpinBox 例子")self.resize(300,…