在SpringBoot项目中的使用Swagger的方法示例
作者:小郑要做干饭人 发布时间:2022-01-04 15:14:39
一. 首先Swagger是什么?
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger官方API文档:https://swagger.io/
作用:
1. 接口的文档在线自动生成。
2. 功能测试。
Swagger的主见介绍:
Swagger Codegen: 通过Codegen 可以将描述文件生成html格式和cwiki形式的接口文档,同时也能生成多钟语言的服务端和客户端的代码。支持通过jar包,docker,node等方式在本地化执行生成。也可以在后面的Swagger Editor中在线生成。
Swagger UI: 提供了一个可视化的UI页面展示描述文件。接口的调用方、测试、项目经理等都可以在该页面中对相关接口进行查阅和做一些简单的接口请求。该项目支持在线导入描述文件和本地部署UI项目。
Swagger Editor: 类似于markendown编辑器的编辑Swagger描述文件的编辑器,该编辑支持实时预览描述文件的更新效果。也提供了在线编辑器和本地部署编辑器两种方式。
Swagger Inspector: 感觉和postman差不多,是一个可以对接口进行测试的在线版的postman。比在Swagger UI里面做接口请求,会返回更多的信息,也会保存你请求的实际请求参数等数据。
Swagger Hub: 集成了上面所有项目的各个功能,你可以以项目和版本为单位,将你的描述文件上传到Swagger Hub中。在Swagger Hub中可以完成上面项目的所有工作,需要注册账号,分免费版和收费版。
PS:
Springfox Swagger: Spring 基于 swagger 规范,可以将基于 SpringMVC 和 Spring Boot 项目的项目代码,自动生成 JSON 格式的描述文件。本身不是属于 Swagger 官网提供的,在这里列出来做个说明,方便后面作一个使用的展开。
二. Swagger UI的使用:
Swagger注解解释:
@Api:请求类的说明
@Api:放在 请求的类上,与 @Controller 并列,说明类的作用,如用户模块,订单类等。
tags="说明该类的作用"
value="该参数没什么意义,所以不需要配置"
常用注解:
- @Api()用于类;
表示标识这个类是swagger的资源
- @ApiOperation()用于方法;
表示一个http请求的操作
- @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等)
- @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收
- @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
- @ApiImplicitParams() 用于方法
包含多个 @ApiImplicitParam
(1). @Api: 请求类的说明
@Api:放在 请求的类上,与 @Controller 并列,说明类的作用,如用户模块,订单类等。
tags="说明该类的作用"
value="描述该类作用" [推荐用这个]
@Api 其它属性配置:
属性名称 备注
value url的路径值
tags 如果设置这个值、value的值会被覆盖
description 对api资源的描述
basePath 基本路径
position 如果配置多个Api 想改变显示的顺序位置
produces 如, “application/json, application/xml”
consumes 如, “application/json, application/xml”
protocols 协议类型,如: http, https, ws, wss.
authorizations 高级特性认证时配置
hidden 配置为true ,将在文档中隐藏
(2). @ApiOperation:方法的说明
@ApiOperation:"用在请求的方法上,说明方法的作用"
value="说明方法的作用"
notes="方法的备注说明"
(3). @ApiImplicitParams、@ApiImplicitParam:方法参数的说明
@ApiImplicitParams:用在请求的方法上,包含一组参数说明
@ApiImplicitParam:对单个参数的说明
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(请求体)--> @RequestBody User user
· form(普通表单提交)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
示例:
@Api(tags="用户模块")
@Controller
public class UserController {
@ApiOperation(value="用户登录",notes="随边说点啥")
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="手机号",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密码",required=true,paramType="form"),
@ApiImplicitParam(name="age",value="年龄",required=true,paramType="form",dataType="Integer")
})
@PostMapping("/login")
public JsonResult login(@RequestParam String mobile, @RequestParam String password,
@RequestParam Integer age){
//...
return JsonResult.ok(map);
}
}
(4). @ApiResponses、@ApiResponse:方法返回值的说明
@ApiResponses:方法返回对象的说明
@ApiResponse:每个参数的说明
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
(5). @ApiModel:用于JavaBean上面,表示一个JavaBean(如:响应数据)的信息
@ApiModel:用于JavaBean的类上面,表示此 JavaBean 整体的信息
(这种一般用在post创建的时候,使用 @RequestBody 这样的场景,
请求参数无法使用 @ApiImplicitParam 注解进行描述的时候 )
(6). @ApiModelProperty:用在JavaBean类的属性上面,说明属性的含义
@ApiModel(description= "返回响应数据")
public class RestMessage implements Serializable{
@ApiModelProperty(value = "是否成功")
private boolean success=true;
@ApiModelProperty(value = "返回对象")
private Object data;
@ApiModelProperty(value = "错误编号")
private Integer errCode;
@ApiModelProperty(value = "错误信息")
private String message;
/* getter/setter 略*/
}
三. Swagger整合SpringBoot
1. Pom依赖:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
2. 配置类:
package com.zhiyou100.configBeans;
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;
/**
* @Author ZhengZiXuan
* @Desc
*/
@Configuration // @Configuration注解,让Spring来加载该类配置。
@EnableSwagger2 //@EnableSwagger2注解来启用Swagger2
public class SwaggerConfigBean {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
*
* @return
*/
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zhiyou100.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("使用Swagger2 构建RESTful APIS - 废物")
.description("废物 - Swagger使用演示")
.termsOfServiceUrl("www.zzxBIuBIuBIu.com")
.version("1.0")
.build();
}
}
3. 正常的Controller再加Swagger注解:
package com.zhiyou100.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Author ZhengZiXuan
* @Desc
*/
@Controller
@Api("测试Swagger 的Controller类")
public class TestController {
@ApiOperation(value="根据id查询名字",notes = "备注:无")
@ApiImplicitParam(name = "id",value = "用户id",required = true,
paramType = "query",dataType = "Integer")
@RequestMapping("/getNameById")
@ResponseBody
public String getNameById(int id){
return "张三";
}
}
4.启动测试:
http://localhost:8080/swagger-ui.html
四. 访问404Bug的解决方法
Swagger UI 界面介绍:
五. Model对象增删改查演示
对User类实现增删改查,生成api文档
package com.zhiyou100.model;
/**
* @Author ZhengZiXuan
* @Date 2021/05/10
* @Desc
*/
public class User {
private int id;
private String name;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(int id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
}
package com.zhiyou100.controller;
import com.zhiyou100.model.User;
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 java.util.ArrayList;
import java.util.List;
/**
* @Author ZhengZiXuan
* @Date 2021/05/10
* @Desc
有点BUG 就是list集合中的增删改
*/
@RestController
@Api("User类的增删改查API")
public class UserController {
ArrayList<User> users = null;
public UserController(){
users = new ArrayList<>();
users.add(new User(1,"张三","123"));
users.add(new User(2,"李四","1234"));
users.add(new User(3,"王五","12345"));
System.out.println("init users "+users);
}
/**
* 根据id查User
*/
@ApiOperation("根据id查用户")
@ApiImplicitParam(name = "id",value = "用户id",
required = true,paramType = "path",
dataType = "Integer")
@RequestMapping(value="/user/get/{id}",method = RequestMethod.GET)
public User getUserById(@PathVariable("id") Integer id){
System.out.println("getUserById id: "+id);
if (id != null){
if (id>0 && id <4){
User user = users.get(id);
System.out.println("getUserById User: "+user);
return user;
}
}
return null;
}
/**
* 查全部user
*/
@ApiOperation("查询全部用户")
@RequestMapping(value="/user/get",method = RequestMethod.GET)
public List<User> getAllUser(){
System.out.println("getAllUser");
return users;
}
/**
* 添加User
*/
@ApiOperation("添加用户")
@ApiImplicitParam(name="user",value = "用户对象",paramType = "body",dataType = "User")
@RequestMapping(value="/user/add",method = RequestMethod.POST)
public User addUser(@RequestBody User user){
System.out.println("addUser User:"+user);
if (user == null || user.getId() == 0){
return null;
}
users.add(user);
return user;
}
/**
* 删除User
*/
@ApiOperation("根据id删除用户")
@ApiImplicitParam(name = "id",value = "用户id",
required = true,paramType = "path",
dataType = "Integer")
@RequestMapping(value="/user/delete/{id}",method = RequestMethod.DELETE)
public boolean delUserById(@PathVariable("id") Integer id){
System.out.println("delUserById id:"+id);
if (id != null){
users.remove(id);
return true;
}
return false;
}
/**
* 更新User
*/
@ApiOperation("根据id更新用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "id",value = "用户id",
required = true,paramType = "path",
dataType = "Integer"),
@ApiImplicitParam(name = "user",value = "用户对象",
required = true,paramType = "body",
dataType = "User")})
@RequestMapping(value="/user/update/{id}",method = RequestMethod.PUT)
public boolean UpdateUserById(@PathVariable("id") Integer id,@RequestBody User user){
System.out.println("UpdateUserById id:"+id+" , User:"+user);
if (id != null && user != null){
users.add(id,user);
return true;
}
return false;
}
}
1. 查询全部:
2. 根据id查:
3. 添加用户:
4.更新用户:
5. 删除用户:
来源:https://blog.csdn.net/a1422655169/article/details/116614173
猜你喜欢
- 目录Jacoco原理简介使用Jacoco生成代码执行覆盖率报告小结Jacoco是Java Code Coverage的缩写,顾名思义,它是获
- Java Comparable 和 Comparator 的详解及区别Java 中为我们提供了两种比较机制:Comparable 和 Com
- java Mybatis存进时间戳封装了一个实体类,里面有个字段 Integer createTime。要利用这个实体类将一个时间戳存进数据
- Spring AOP底层原理代理模式一、什么是 AOPAOP 就是面向切面编程,是 OOP(面向对象编程)的延续。利用 AOP 可以对业务逻
- 本文实例分析了java中transient关键字用法。分享给大家供大家参考。具体分析如下:java有个特点就是序列化,简单地来说就是可以将这
- Java CharArrayReader流一、CharArrayReader流定义API说明:该类实现了一个可用作字符输入流的字符缓冲区,即
- 在Spring mvc的开发中,我们可以通过RequestMapping来配,当前方法用于处理哪一个URL的请求.同样我们现在有一个需求,有
- 面试中会经常遇到手撕代码的情况,而求TopK的是经常遇到的题目。下面我就用Java来实现。主要通过两种方法实现,快排思想以及堆排序的思想,两
- 快速排序快速排序是一种比较高效的排序算法,采用“分而治之”的思想,通过多次比较和交换来实现排序,在一
- 使用Mybatis-Plus的SqlSessionFactory问题前些日子工作中出现一个问题,项目中使用了MybatisPlus,然后出现
- 背景最近让我做一个大数据的系统,分析了一下,麻烦的地方就是多数据源切换抽取数据。考虑到可以跨服务器跨数据库抽数,再整理数据,就配置了这个动态
- 这篇文章主要介绍了java io读取文件操作代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友
- 目录一、什么是 RUNNABLE?二、与传统的ready状态的区别三、与传统的running状态的区别四、当I/O阻塞时五、如何看待RUNN
- ✨字符, 字节与字符串🎈字符与字符串字符串内部包含一个字符数组,String 可以和 char[] 相互转换.NO方法名称类型描述1publ
- G将军有一支训练有素的军队,这个军队除开G将军外,每名士兵都有一个直接上级(可能是其他士兵,也可能是G将军)。现在G将军将接受一个特别的任务
- 为开发团队选择一款优秀的MVC框架是件难事儿,在众多可行的方案中决择需要很高的经验和水平。你的一个决定会影响团队未来的几年。要考虑方面太多:
- 使用@Value取值出现的问题在springBoot项目中我们一般会把一些路径或者资源写在配置文件中,方便管理。但是取得时候有可能会出现一些
- 在为什么阿里巴巴不建议在for循环中使用”+”进行字符串拼接一文中,我们介绍了几种Java中字符串拼接的方式,以及优缺点。其中还有一个重要的
- Java内存区域与内存溢出异常概述对于 C 和 C++程序开发的开发人员来说,在内存管理领域,程序员对内存拥有绝对的使用权,但是也要主要到正
- 一、int还记得 C 语言里的 int 吗,C里面的 int 有着无符号与有符号之分但是Java内就没有,且固定占4个字节大小,也就是32比