一,什么是swagger?

1,  Swagger 是一个规范和完整的文档框架,

用于生成、描述、调用和可视化 RESTful 风格的 Web 服务文档

官方网站:

https://swagger.io/

2,使用swagger要注意的地方:

在生产环境中必须关闭swagger,

它本身只用于前后端工程师之间的沟通,

可以专门使用一台内部服务器来展示ui供访问,

即使在这上面要做好安全措施

3,  因为swagger3.0.0已发布,本文使用了最新版

如果有还在用2.x版本的请参考时注意区分

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

对应的源码可以访问这里获取: https://github.com/liuhongdi/

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,演示项目的相关信息

1,项目地址

https://github.com/liuhongdi/swagger3

2,项目功能说明

演示了使用swagger3.0.0生成接口站的文档,

包括:通用的全局参数,

响应时各种状态的返回

响应的封装后的result格式数据

3,项目结构:如图:

三,配置文件说明

1,pom.xml

        <dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

说明:用springfox-boot-starter来引入swagger

2,application.properties

springfox.documentation.swagger-ui.enabled=true

说明:在生产环境中要设置swagger-ui的enabled值为false,

用来关闭文档的显示

四,java文件说明:

1,Swagger3Config.java

@EnableOpenApi
@Configuration
public class Swagger3Config implements WebMvcConfigurer { @Bean
public Docket createRestApi() {
//返回文档摘要信息
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
.paths(PathSelectors.any())
.build()
.globalRequestParameters(getGlobalRequestParameters())
.globalResponses(HttpMethod.GET, getGlobalResonseMessage())
.globalResponses(HttpMethod.POST, getGlobalResonseMessage());
} //生成接口信息,包括标题、联系人等
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文档")
.description("如有疑问,请联系开发工程师老刘。")
.contact(new Contact("刘宏缔", "https://www.cnblogs.com/architectforest/", "371125307@qq.com"))
.version("1.0")
.build();
} //生成全局通用参数
private List<RequestParameter> getGlobalRequestParameters() {
List<RequestParameter> parameters = new ArrayList<>();
parameters.add(new RequestParameterBuilder()
.name("appid")
.description("平台id")
.required(true)
.in(ParameterType.QUERY)
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.required(false)
.build());
parameters.add(new RequestParameterBuilder()
.name("udid")
.description("设备的唯一id")
.required(true)
.in(ParameterType.QUERY)
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.required(false)
.build());
parameters.add(new RequestParameterBuilder()
.name("version")
.description("客户端的版本号")
.required(true)
.in(ParameterType.QUERY)
.query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
.required(false)
.build());
return parameters;
} //生成通用响应信息
private List<Response> getGlobalResonseMessage() {
List<Response> responseList = new ArrayList<>();
responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
return responseList;
}
}

说明:生成了全局的参数和通用的响应信息

2,RestResult.java

@ApiModel("api通用返回数据")
public class RestResult<T> { //uuid,用作唯一标识符,供序列化和反序列化时检测是否一致
private static final long serialVersionUID = 7498483649536881777L;
//标识代码,0表示成功,非0表示出错
@ApiModelProperty("标识代码,0表示成功,非0表示出错")
private Integer code; //提示信息,通常供报错时使用
@ApiModelProperty("提示信息,供报错时使用")
private String msg; //正常返回时返回的数据
@ApiModelProperty("返回的数据")
private T data; //constructor
public RestResult() {
} //constructor
public RestResult(Integer status, String msg, T data) {
this.code = status;
this.msg = msg;
this.data = data;
} //返回成功数据
public RestResult success(T data) {
return new RestResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), data);
} public static RestResult success(Integer code,String msg) {
return new RestResult(code, msg, null);
} //返回出错数据
public static RestResult error(ResponseCode code) {
return new RestResult(code.getCode(), code.getMsg(), null);
} public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
} public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
} public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}

说明:这里要注意使用泛型T,如果只用Object,则swagger不能识别我们所返回的数据的类型说明:

其中:ApiModel用于类上面说明功能,

ApiModelProperty用于字段上说明功能

尤其是getData方法的返回数据类型,要用T,使用工具生成的data类容易出现这种错误,

3,Goods.java

@ApiModel("商品模型")
public class Goods {
//商品id
@ApiModelProperty("商品id")
Long goodsId;
public Long getGoodsId() {
return this.goodsId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
} //商品名称
@ApiModelProperty("商品名称")
private String goodsName;
public String getGoodsName() {
return this.goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
} //商品标题
@ApiModelProperty("商品标题")
private String subject;
public String getSubject() {
return this.subject;
}
public void setSubject(String subject) {
this.subject = subject;
} //商品价格
@ApiModelProperty("商品价格")
private BigDecimal price;
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
} //库存
@ApiModelProperty("商品库存")
int stock;
public int getStock() {
return this.stock;
}
public void setStock(int stock) {
this.stock = stock;
} public String toString(){
return " Goods:goodsId=" + goodsId +" goodsName=" + goodsName+" subject=" + subject+" price=" + price+" stock=" + stock;
}
}

4,GoodsController.java

@Api(tags = "商品信息管理接口")
@RestController
@RequestMapping("/goods")
public class GoodsController { @Operation(summary = "商品详情,针对得到单个商品的信息")
@GetMapping("/one")
public RestResult<Goods> one(@Parameter(description = "商品id,正整数") @RequestParam(value="goodsid",required = false,defaultValue = "0") Integer goodsid) {
Goods goodsone = new Goods();
goodsone.setGoodsId(3L);
goodsone.setGoodsName("电子书");
goodsone.setSubject("学python,学ai");
goodsone.setPrice(new BigDecimal(60));
goodsone.setStock(10);
RestResult res = new RestResult();
return res.success(goodsone);
} @Operation(summary = "提交订单")
@PostMapping("/order")
@ApiImplicitParams({
@ApiImplicitParam(name="userid",value="用户id",dataTypeClass = Long.class, paramType = "query",example="12345"),
@ApiImplicitParam(name="goodsid",value="商品id",dataTypeClass = Integer.class, paramType = "query",example="12345"),
@ApiImplicitParam(name="mobile",value="手机号",dataTypeClass = String.class, paramType = "query",example="13866668888"),
@ApiImplicitParam(name="comment",value="发货备注",dataTypeClass = String.class, paramType = "query",example="请在情人节当天送到")
}) public RestResult<String> order(@ApiIgnore @RequestParam Map<String,String> params) {
System.out.println(params);
RestResult res = new RestResult();
return res.success("success");
}
}

说明:Api用来指定一个controller中的各个接口的通用说明

Operation:用来说明一个方法

@ApiImplicitParams:用来包含多个包含多个 @ApiImplicitParam,

@ApiImplicitParam:用来说明一个请求参数

如果使用@Parameter来做说明,可以直接加到@RequestParam参数之前

@ApiIgnore:用来忽略不必要显示的参数

五,效果测试

1,访问文档:访问:

http://127.0.0.1:8080/swagger-ui/index.html

可以看到已有的接口:

2,查看接口的详情:

参数:可以看到我们添加的全局通用参数

响应:

六,查看spring boot的版本

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)

spring boot:用swagger3生成接口文档,支持全局通用参数(swagger 3.0.0 / spring boot 2.3.2)的更多相关文章

  1. Spring Boot Swagger2自动生成接口文档

    一.简介 在当下这个前后端分离的技术趋势下,前端工程师过度依赖后端工程师的接口和数据,给开发带来了两大问题: 1.问题一.后端接口查看难:要怎么调用?参数怎么传递?有几个参数?参数都代表什么含义? 2 ...

  2. SpringBoot整合Swagger3生成接口文档

    前后端分离的项目,接口文档的存在十分重要.与手动编写接口文档不同,swagger是一个自动生成接口文档的工具,在需求不断变更的环境下,手动编写文档的效率实在太低.与swagger2相比新版的swagg ...

  3. 接口文档管理工具-Postman、Swagger、RAP(转载)

    接口文档管理工具-Postman.Swagger.RAP 转自:http://www.51testing.com/html/10/n-3715910.html 在项目开发测试中,接口文档是贯穿始终的. ...

  4. Spring Boot(九)Swagger2自动生成接口文档和Mock模拟数据

    一.简介 在当下这个前后端分离的技术趋势下,前端工程师过度依赖后端工程师的接口和数据,给开发带来了两大问题: 问题一.后端接口查看难:要怎么调用?参数怎么传递?有几个参数?参数都代表什么含义? 问题二 ...

  5. Spring boot 添加日志 和 生成接口文档

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring- ...

  6. Java | Spring Boot Swagger2 集成REST ful API 生成接口文档

      Spring Boot Swagger2 集成REST ful API 生成接口文档 原文 简介 由于Spring Boot 的特性,用来开发 REST ful 变得非常容易,并且结合 Swagg ...

  7. Springboot集成swagger2生成接口文档

    [转载请注明]: 原文出处:https://www.cnblogs.com/jstarseven/p/11509884.html    作者:jstarseven    码字挺辛苦的.....   一 ...

  8. spring-boot-route(六)整合JApiDocs生成接口文档

    上一篇文章中介绍了使用Swagger生成接口文档,非常方便,功能也十分强大.如果非要说Swaager有什么缺点,想必就是注解写起来比较麻烦.如果我说有一款不用写注解,就可以生成文档的工具,你心动了吗? ...

  9. SpringBoot接口 - 如何生成接口文档之非侵入方式(通过注释生成)Smart-Doc?

    通过Swagger系列可以快速生成API文档,但是这种API文档生成是需要在接口上添加注解等,这表明这是一种侵入式方式: 那么有没有非侵入式方式呢, 比如通过注释生成文档? 本文主要介绍非侵入式的方式 ...

随机推荐

  1. ajax之---原生ajax

    原生ajax,基于XMLHttpRequest对象来完成请求 <!DOCTYPE html><html><head lang="en">    ...

  2. JavaScript 流程控制-循环

    1.循环 循环目的 在实际问题中,有许多具有规律性的重复操作,因此在程序中要完成这类操作就需要重复执行某些语句 JS中的循环 在JS中,主要有三种类型的循环语句: for循环 while循环 do.. ...

  3. JVM运行时数据区划分

    Java内存空间 内存是非常重要的系统资源,是硬盘和cpu的中间仓库及桥梁,承载着操作系统和应用程序的实时运行.JVM内存布局规定了JAVA在运行过程中内存申请.分配.管理的策略,保证了JVM的高效稳 ...

  4. 国产化之路-麒麟V10操作系统安装.net core 3.1 sdk

    随着芯片国产化,操作系统国产化,软件国产化的声浪越来越高,公司也已经把开发项目国产化提上了日程,最近搞来了台长城的国产化电脑主机,用来搞试验,安装的是麒麟V10的操作系统,国产化折腾之路就此开始,用的 ...

  5. 深入理解java虚拟机--垃圾收集器

    对象的销毁 对象的finalize方法只会执行一次,在finalize里可以自救不被销毁,二次被主动gc,必定会销毁 类销毁

  6. hystrix源码小贴士之之hystrix-metrics-event-stream

    hystrix-metrics-event-stream主要提供了一些servlet,可以让用户通过http请求获取metrics信息. HystrixSampleSseServlet 继承了Http ...

  7. powershell中使用Send-MailMessage发送邮件

    在powershell中我们可以使用Send-MailMessage发送邮件,一般都是有这个命令的 笔者的总结是鉴于公司的环境的,大家在借鉴时,需要根据自己的实际情况进行修改 1.你笔者测试的格式如下 ...

  8. PHP序列化与反序列化学习

    序列化与反序列化学习 把对象转换为字节序列的过程称为对象的序列化:把字节序列恢复为对象的过程称为对象的反序列化. <?php class UserInfo { public $name = &q ...

  9. Ribbon自定义负载均衡策略,在网关实现类似Ip_hash的负载均衡,ribbon给单个服务配置属性

    背景: 我需要在网关实现一种功能,某个用户的请求永远打在后台指定的服务,也就是根据ip地址进行负载均衡 原理: 在ribbon的配置类下: 那我们自己创建一个IRule的实现类,模仿ZoneAvoid ...

  10. unity 3d 三、空间与运动

    3D游戏编程第三次作业 简答并用程序验证[建议做] 游戏对象运动的本质是什么? 游戏对象运动的本质是游戏对象Position.Rotate.Scale属性数值的变化. 请用三种方法以上方法,实现物体的 ...