当前位置:网站首页>Swagger的简单介绍,集成,以及如何在生产环境中关闭swagger,在测试和开发环境中自动打开
Swagger的简单介绍,集成,以及如何在生产环境中关闭swagger,在测试和开发环境中自动打开
2022-08-02 06:14:00 【爱学习的大雄】
文章目录
引言
本篇文章前面部分讲解了何为Swagger,在项目中该如何去使用,以及注解及其相关说明,如果是想要了解如何去动态的关闭Swagger的,通过目录链接直接跳转即可
1、什么是swagger?
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。
2、swagger的作用是什么?
1)接口的文档在线自动生成。
2)功能测试。
3、swagger如何使用?
这里建议swagger2的版本为2.9.2,springboot的版本为2.5.5以下,否则可能会出现空指针异常的问题
第一步:导入swagger依赖包
<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>
第二步:创建swagger配置文件
如果只是需要在项目中简单使用以下使用方式1即可
方式一
/** * Swagger2的接口配置 */
@Configuration
@EnableSwagger2
@Profile({
"dev", "test"})
public class SwaggerConfig {
/** * 系统基础配置 */
@Autowired
private RpcsConfig rpcsConfig;
/** * 创建API */
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/dev-api")
// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
.apiInfo(apiInfo())
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
//.apis(RequestHandlerSelectors.basePackage("com.ryi.rpcs.project.tool.swagger"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
/* 设置安全模式,swagger可以设置访问token */
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
/** * 添加摘要信息 */
private ApiInfo apiInfo() {
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("标题:快速预安检系统_接口文档")
// 描述
.description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
// 作者信息
.contact(new Contact(rpcsConfig.getName(), null, null))
// 版本
.version("版本号:" + rpcsConfig.getVersion())
.build();
}
}
方式二
package com.ryi.rpcs.framework.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/** * Swagger2的接口配置 */
@Configuration
@EnableSwagger2
@Profile({
"dev", "test"})
public class SwaggerConfig {
/** * 系统基础配置 */
@Autowired
private RpcsConfig rpcsConfig;
/** * 创建API */
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/dev-api")
// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
.apiInfo(apiInfo())
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
//.apis(RequestHandlerSelectors.basePackage("com.ryi.rpcs.project.tool.swagger"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
/* 设置安全模式,swagger可以设置访问token */
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
/** * 安全模式,这里指定token通过Authorization头请求头传递 */
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList = new ArrayList<ApiKey>();
apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
return apiKeyList;
}
/** * 安全上下文 */
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build());
return securityContexts;
}
/** * 默认的安全上引用 */
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
/** * 添加摘要信息 */
private ApiInfo apiInfo() {
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("标题:快速预安检系统_接口文档")
// 描述
.description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
// 作者信息
.contact(new Contact(rpcsConfig.getName(), null, null))
// 版本
.version("版本号:" + rpcsConfig.getVersion())
.build();
}
}
4、注解及其说明
@Api : 用在类上,描述该类的主要作用。
@ApiOperation:用在方法上,给API增加方法描述。
@ApiImplicitParams : 用在方法上,包含一组参数描述。
@ApiImplicitParam:用来注解来给方法入参增加描述。
@ApiResponses:用于表示一组响应。
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息。
- code:数字,例如500
- message:信息,例如"请求参数异常"
- response:抛出异常的类
@ApiModel:用在返回对象类上,描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)。
@ApiModelProperty:描述一个model的属性。
关闭Swagger的三种方式
方式一:
在Swagger2Config上使用@Profile注解标识,@Profile({“dev”,“test”})表示在dev和test环境才能访问swagger-ui.html,prod环境下访问不了。
方式二:
在Swagger2Config上使用@ConditionalOnProperty注解,
@ConditionalOnProperty(name = “swagger.enable”, havingValue = “true”)
表示配置文件中如果swagger.enable =true表示开启。所以只需要在开发环境的配置文件配置为true,生产环境配置为false即可。
方式三:
在application.yml
中写一个swagger.enable=true
或swagger.enable=false
的值,之后在SwaggerConfig类中通过@Value("${swagger.enable}")
读取其值,对swagger配置中的enable
进行动态属性赋值开关即可
= “true”)**
表示配置文件中如果swagger.enable =true表示开启。所以只需要在开发环境的配置文件配置为true,生产环境配置为false即可。
方式三:
在application.yml
中写一个swagger.enable=true
或swagger.enable=false
的值,之后在SwaggerConfig类中通过@Value("${swagger.enable}")
读取其值,对swagger配置中的enable
进行动态属性赋值开关即可
个人比较喜欢第一种方式,因为第二种方式还要在每个环境文件中去配置,并维护;Swagger一般用于开发和测试环境,所以直接限制Swagger启用的环境为dev和test即可,这样也不需要再维护配置文件了。
边栏推荐
- 两篇不错的php debug教程
- request.getSession(), the story
- PHP Warning: putenv() has been disabled for security reasons in phar
- 返回文件名问题
- Launch Space on-premises deployment (local) Beta!
- .NET静态代码织入——肉夹馍(Rougamo) 发布1.1.0
- odoo field 设置匿名函数domain
- Dataset: A detailed guide to the download link collection of commonly used datasets in machine learning
- 推出 Space On-Premises (本地部署版) Beta 版!
- zabbix auto-discovery and auto-registration
猜你喜欢
推出 Space On-Premises (本地部署版) Beta 版!
HCIP 第四天
Leading the demand and justifying the HR value - the successful launch of the "Human Resource Leading Model HRLM"
Ant three sides: MQ message loss, duplication, backlog problem, what are the solutions?
Expert Insights | 3 ways to seize innovation opportunities in a downturn
Nodejs安装教程
The stock price has repeatedly hit new lows, and the real estate SaaS giant is in trouble. How should Mingyuan Cloud transform and save itself?
[Dataset][VOC] Male and female dataset voc format 6188 sheets
MySQL union query (multi-table query)
MySQL Advanced Study Notes
随机推荐
APP专项测试:流量测试
8/1 思维+扩展欧几里得+树上dp
【21天学习挑战赛】顺序查找
typescript ‘props‘ is declared but its value is never read 解决办法
Launch Space on-premises deployment (local) Beta!
MySQL高级语句(一)
Py's mlxtend: a detailed guide to the introduction, installation, and usage of the mlxtend library
看图就懂|衡量业务增长健康的销售指标如何选择
aTrust项目的相关操作与分享
chrome plugin development guide
【暑期每日一题】洛谷 P1551 亲戚
振兴农村循环经济 和数链串起农业“生态链”
How does abaqus quickly import the assembly of other cae files?
Project development specification
MySQL Advanced SQL Statements
Connection reset by peer problem analysis
MySql 5.7.38下载安装教程 ,并实现在Navicat操作MySql
Nodejs安装教程
At age 94, pioneer Turing award winner, computational complexity theory, Juris Hartmanis, died
Clapper that can interact with the audience in real time