资料

  • swagger 官网:swagger.io

  • springfox 官网:springfox

  • springfox Github 仓库:springfox / springfox

  • springfox-demos Github 仓库:springfox / springfox-demos

  • springfox Maven 仓库:Home » io.springfox

Swagger介绍

Swagger 是一套基于 OpenAPI 规范(OpenAPI Specification,OAS)构建的开源工具,可以帮助我们设计、构建、记录以及使用 REST API。

OpenAPI规范是在2015年由OpenAPI Initiative捐赠给Linux基金会的。该规范创建了RESTful接口,可通过有效映射与之关联的所有资源和操作来轻松开发和使用API​​。

Swagger 主要包含了以下三个部分:

  • Swagger Editor:基于浏览器的编辑器,我们可以使用它编写我们 OpenAPI 规范。
  • Swagger UI:它会将我们编写的 OpenAPI 规范呈现为交互式的 API 文档,后文我将使用浏览器来查看并且操作我们的 Rest API。
  • Swagger Codegen:它可以通过为 OpenAPI(以前称为 Swagger)规范定义的任何 API 生成服务器存根和客户端 SDK 来简化构建过程。

Springfox介绍

Springfox的Java库套件旨在自动生成使用spring系列项目编写的JSON API的机器和人类可读规范。

Springfox的工作原理是在运行时检查应用程序,以基于Spring配置,类结构和各种编译时Java注释来推断API语义。

Springfox从最初由Marty Pitt创建的项目演变而来,并被命名为 swagger-springmvc。

通常SpringBoot项目整合swagger需要用到两个依赖:springfox-swagger2springfox-swagger-ui,用于自动生成swagger文档。

  • springfox-swagger2:这个组件的功能用于帮助我们自动生成描述API的json文件
  • springfox-swagger-ui:就是将描述API的json文件解析出来,用一种更友好的方式呈现出来。

SpringFox 3.0.0 发布

官方说明:

  • SpringFox 3.0.0 发布了,SpringFox 的前身是 swagger-springmvc,是一个开源的 API doc 框架,可以将 Controller 的方法以文档的形式展现。
  • 首先,非常感谢社区让我有动力参与这个项目。在这个版本中,在代码、注释、bug报告方面有一些非常惊人的贡献,看到人们在问题论坛上跳槽来解决问题,我感到很谦卑。它确实激励我克服“困难”,开始认真地工作。有什么更好的办法来摆脱科维德的忧郁!
  • 注意:这是一个突破性的变更版本,我们已经尽可能地保持与springfox早期版本的向后兼容性。在2.9之前被弃用的api已经被积极地删除,并且标记了将在不久的将来消失的新api。所以请注意这些,并报告任何遗漏的内容。

新特性:

  • Remove explicit dependencies on springfox-swagger2
  • Remove any @EnableSwagger2… annotations
  • Add the springfox-boot-starter dependency
  • Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces.

此版本的亮点:

  • Spring5,Webflux支持(仅支持请求映射,尚不支持功能端点)。
  • Spring Integration支持(非常感谢反馈)。
  • SpringBoot支持springfox Boot starter依赖性(零配置、自动配置支持)。
  • 具有自动完成功能的文档化配置属性。
  • 更好的规范兼容性与2.0。
  • 支持OpenApi 3.0.3。
  • 零依赖。几乎只需要spring-plugin,swagger-core ,现有的swagger2注释将继续工作并丰富openapi3.0规范。

兼容性说明:

  • 需要Java 8
  • 需要Spring5.x(未在早期版本中测试)
  • 需要SpringBoot 2.2+(未在早期版本中测试)

注意:

应用主类增加注解@EnableOpenApi,删除之前版本的SwaggerConfig.java。

启动项目,访问地址:http://localhost:8080/swagger-ui/index.html

附:2.x版本中访问的地址的为http://localhost:8080/swagger-ui.html

整合使用

Maven项目中引入springfox-boot-starter依赖:

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

application.yml配置

spring:application:name: springfox-swagger
server:port: 8080# ===== 自定义swagger配置 ===== #
swagger:enable: trueapplication-name: ${spring.application.name}application-version: 1.0application-description: springfox swagger 3.0整合Demotry-host: http://localhost:${server.port}

使用@EnableOpenApi注解,启用swagger配置

@EnableOpenApi
@Configuration
public class SwaggerConfiguration {}

自定义swagger配置类SwaggerProperties

@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties {/*** 是否开启swagger,生产环境一般关闭,所以这里定义一个变量*/private Boolean enable;/*** 项目应用名*/private String applicationName;/*** 项目版本信息*/private String applicationVersion;/*** 项目描述信息*/private String applicationDescription;/*** 接口调试地址*/private String tryHost;public Boolean getEnable() {return enable;}public void setEnable(Boolean enable) {this.enable = enable;}public String getApplicationName() {return applicationName;}public void setApplicationName(String applicationName) {this.applicationName = applicationName;}public String getApplicationVersion() {return applicationVersion;}public void setApplicationVersion(String applicationVersion) {this.applicationVersion = applicationVersion;}public String getApplicationDescription() {return applicationDescription;}public void setApplicationDescription(String applicationDescription) {this.applicationDescription = applicationDescription;}public String getTryHost() {return tryHost;}public void setTryHost(String tryHost) {this.tryHost = tryHost;}
}

一个完整详细的springfox swagger配置示例:

import io.swagger.models.auth.In;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;import java.lang.reflect.Field;
import java.util.*;@EnableOpenApi
@Configuration
public class SwaggerConfiguration implements WebMvcConfigurer {private final SwaggerProperties swaggerProperties;public SwaggerConfiguration(SwaggerProperties swaggerProperties) {this.swaggerProperties = swaggerProperties;}@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.OAS_30).pathMapping("/")// 定义是否开启swagger,false为关闭,可以通过变量控制.enable(swaggerProperties.getEnable())// 将api的元信息设置为包含在json ResourceListing响应中。 .apiInfo(apiInfo())// 接口调试地址.host(swaggerProperties.getTryHost())// 选择哪些接口作为swagger的doc发布.select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build()// 支持的通讯协议集合.protocols(newHashSet("https", "http"))// 授权信息设置,必要的header token等认证信息.securitySchemes(securitySchemes())// 授权信息全局应用.securityContexts(securityContexts());}/*** API 页面上半部分展示信息*/private ApiInfo apiInfo() {return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc").description(swaggerProperties.getApplicationDescription()).contact(new Contact("lighter", null, "123456@gmail.com")).version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion()).build();}/*** 设置授权信息*/private List<SecurityScheme> securitySchemes() {ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());return Collections.singletonList(apiKey);}/*** 授权信息全局应用*/private List<SecurityContext> securityContexts() {return Collections.singletonList(SecurityContext.builder().securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")}))).build());}@SafeVarargsprivate final <T> Set<T> newHashSet(T... ts) {if (ts.length > 0) {return new LinkedHashSet<>(Arrays.asList(ts));}return null;}/*** 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息*/@SuppressWarnings("unchecked")@Overridepublic void addInterceptors(InterceptorRegistry registry) {try {Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);if (registrations != null) {for (InterceptorRegistration interceptorRegistration : registrations) {interceptorRegistration.excludePathPatterns("/swagger**/**").excludePathPatterns("/webjars/**").excludePathPatterns("/v3/**").excludePathPatterns("/doc.html");}}} catch (Exception e) {e.printStackTrace();}}}

一些常用注解说明

  • @Api:用在controller类,描述API接口
  • @ApiOperation:描述接口方法
  • @ApiModel:描述对象
  • @ApiModelProperty:描述对象属性
  • @ApiImplicitParams:描述接口参数
  • @ApiResponses:描述接口响应
  • @ApiIgnore:忽略接口方法

示例

项目Demo:springfox-swagger

效果图:

参考

  • 在 Spring Boot 项目中使用 Swagger 文档
  • Springfox 3.0.0(包含springfox-swagger2-3.0.0)即OpenAPI 3的发布与系统集成

Spring Boot 整合 springfox-swagger 3.0.0相关推荐

  1. Spring Boot 整合 Swagger

    一.为什么要用 Swagger 现在的开发模式,一般都是前后端分离的,开发接口文档就显得尤为重要,前端人员需要按照后端的功能文档调用对应的接口.在没有使用 API 文档之前,很多公司都是在纸或者 Ma ...

  2. Spring Boot 整合Swagger实现API管理

    Spring Boot 整合Swagger实现API管理 1 Swagger介绍 根据官网的介绍: https://swagger.io Swagger 是一款RESTFUL接口的.基于YAML.JS ...

  3. springfox源码_Spring boot整合Springfox在线生成restful的api doc

    Springfox是什么,有什么用? Springfox基于Swagger,能更方便的集成到spring boot 中,Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTf ...

  4. Spring Boot整合Swagger3配置全局Token

    应用背景:Swagger配置全局Token的目的在于调用真正接口前会被相关拦截器拦截,拦截器会校验此次访问是否合法,这时配置全局Token的作用就显现出来了,全局Token可以存储所有接口访问时的令牌 ...

  5. Spring Boot整合Swagger3注解@ApiImplicitParam的paramType属性为“path“

    Spring Boot整合Swagger3的依赖版本为: <!--引入SpringBoot整合Swagger3的依赖--> <dependency><groupId> ...

  6. Spring Boot整合Swagger3注解@ApiImplicitParam的allowMultiple属性

    Spring Boot整合Swagger3的依赖版本为: <!--引入SpringBoot整合Swagger3的依赖--> <dependency><groupId> ...

  7. 在spring boot中集成Swagger

    Swagger 在spring boot中集成Swagger 新建一个swagger项目 maven依赖 <!-- https://mvnrepository.com/artifact/io.s ...

  8. Spring Boot 整合——Spring Boot整合kafka整合

    Spring Boot 整合之前的内容 项目名称 描述 地址 base-data-mybatis 整合mybatis-plus(实际上官方教程已经很多,只做了自定义插件) 未完成 base-jpa J ...

  9. Spring Boot整合RSA加密数据传输

    简介 吹水时间开始了,是这样的,公司自研开发一个app,因为要运营和上架需要办理安全评估,办理中说到公司app有可能会泄露用户信息,对用户信息没有加密,遇到抓包的可能会导致用户信息泄露,这时我想到了R ...

  10. Spring Boot 2.X - Spring Boot整合Swagger2(starter方式)

    文章目录 Spring Boot 2.X - Spring Boot整合Swagger2(starter方式) 引入依赖 添加@EnableSwagger2Doc注解 创建实体类 创建Controll ...

最新文章

  1. 几种典型磁铁表面的磁感应强度的变化
  2. 羊皮卷的故事-第二章
  3. 手机通过WIFI连上ZXV10 H618B路由器但不能上网问题的解决
  4. oracle时间类型插入,oracle 插入时间字符串 Date类型
  5. [JavaWeb-MySQL]SQL基本概念,通用语法,分类
  6. linux sybase 自动备份,Linux平台下Sybase数据库备份方法分析.doc
  7. 关于js中正则表达式链接
  8. 多条数据取第一条_tp框架查询数据
  9. does not esixt in the current content error
  10. 扩展 delphi 泛型 以实现类似lambda功能 , C#中的any count first last 等扩展方法
  11. c语言答案网站,c语言习题及答案
  12. SD与SE的关系,以及异常值
  13. 基于MATLAB的极限与求导(附完整代码)
  14. 防止电脑被木马迫害,检测和寻找木马隐藏的位置
  15. CIFAR10图像分类ResNet模型实战(pytorch)
  16. BZOJ3527 力
  17. 移植facenet pb模型到android
  18. Oracle 19c Grid Infrastructure安装
  19. python怎么同时对多行代码进行注释?
  20. fi选项 电脑没有连接wi,没有电脑怎么设置无线路由器?

热门文章

  1. 谭浩强C++ 第十三章
  2. MakePic.com 图片制造 打造个性签名 拒绝垃圾邮件 生成个性印章
  3. 常用开发(Case-计算机辅助软件工程)工具分类
  4. 自己写的 轮播插件 仿多玩
  5. 子串查找(字符串匹配)
  6. 11. 缺页中断处理概述
  7. AI改变金融风控,深度学习技术可以将坏账降低35% | 干货
  8. VHDL键盘消抖动电路原理图及4×4键盘完整代码
  9. python调用aspen_用Matlab与Aspen Plus通信
  10. 2023最新帝国CMS7.5仿《优优健康网》网站模板源码+UI美观简约大气