一、Swagger是什么
swagger的诞生的一个背景是,前后端开发人员的关于API文档交流的一个产物。前端人员要集成相关功能,则必须要有相关API文档。
当然API文档可以自己手写维护,但是存在以下几个问题
- 文档书写,增加工作量。
- 需求不是一定的,往往会出现些许调整。文档未必能及时调整,影响集成。
- swagger拥有美观的界面
所以,swagger就很有必要在项目中使用。我们可以通过注解的形式,编写API文档。
二、SpringBoot 整合 Swagger
maven依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
swaggerConfigure
- @configuration (配置类必备)
- @EnableSwagger2 (开启Swagger2支持)
- @Bean(生成Bean对象,交个Spring管理,我们要生成
Docket
对象)
(1)Docket
对象的创建
new Docket(DocumentationType.SWAGGER_2)
.host(swaggerProperties.getHost())
.apiInfo(apiInfo(swaggerProperties))
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
.paths(Predicates.and(urls))
.build()
.securitySchemes(Collections.singletonList(securitySchemes(swaggerProperties)))
.securityContexts(Collections.singletonList(securityContexts(swaggerProperties)));
DocumentationType.SWAGGER_2
设置文档类型,源自springfox.documentation.spi.DocumentationType
host
设置暴露端口
select
初始化api选择器ApiSelectorBuilder
apiInfo
设置文档信息
new ApiInfoBuilder()
.title(swaggerProperties.getTitle()) // 设置文档标题
.description(swaggerProperties.getDescription()) // 设置文档描述
.version(swaggerProperties.getVersion()) // 设置版本
.build();
paths
设置扫描路径
securitySchemes
配置鉴权参数
securityContexts
设置鉴权的接口
(2) swagger常用注解
swagger常用注解
(3)Swagger集成思维导图
三、SpringCloud整合Swagger
- 配置swagger配置类,放入公共模块当中
- 通过spring.factories,注入spring容器
- 涉及模块引入公共模块
- gateway中设置要开放的端口