提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
本文针对springboot项目轻松引入swagger做一个示例。
一、Swagger是什么?
Swagger 是一个用于生成、描述和调用 RESTful 接口的 Web 服务。通俗的来讲,Swagger 就是将项目中所有(想要暴露的)接口展现在页面上,并且可以进行接口调用和测试的服务。 PS:Swagger 遵循了 OpenAPI 规范,OpenAPI 是 Linux 基金会的一个项目,试图通过定义一种用来描述 API 格式或 API 定义的语言,来规范 RESTful 服务开发过程。 Swagger 官网地址:https://swagger.io/Swagger 有什么用?从上述 Swagger 定义我们不难看出 Swagger 有以下 3 个重要的作用:将项目中所有的接口展现在页面上,这样后端程序员就不需要专门为前端使用者编写专门的接口文档;当接口更新之后,只需要修改代码中的 Swagger 描述就可以实时生成新的接口文档了,从而规避了接口文档老旧不能使用的问题;通过 Swagger 页面,我们可以直接进行接口调用,降低了项目开发阶段的调试成本。
二、使用步骤
1.pom导入swagger包以及knief
代码如下(示例):
<properties>
<swagger.version>2.9.2</swagger.version>
<knife4j.version>2.0.2</knife4j.version>
</properties>
<!-- 在dependencies标签下添加如下, knife,是 swagger 的增强版,同一个作者开发。该UI增强包主要包括两大核心功能:文档说明 和 在线调试 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
2.添加swagger配置类
代码如下(示例):
package com.dianhun.corporate.compliance.config;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.dianhun.corporate.compliance"))
.paths(PathSelectors.any())
.build();
// .globalOperationParameters(setHeaderToken());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.description("文档描述")
.title("接口文档")
.version("1.0")
.build();
}
}
总结
以上,就能轻松使用swagger调试了。
版权声明:本文为Ver_rev原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。