1.Swagger2的介绍

什么是swagger2

编写和维护接口文档是每个程序员的职责,根据Swagger2可以快速帮助我们编写最新的API接口文档,再也不用担心开会前仍忙于整理各种资料了,间接提升了团队开发的沟通效率。

常用注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息等等

@Api:修饰整个类,描述Controller的作用

@ApiOperation:描述一个类的一个方法,或者说一个接口

@ApiParam:单个参数描述

@ApiModel:用对象来接收参数

@ApiModelProperty:用对象接收参数时,描述对象的一个字段

@ApiImplicitParam:一个请求参数

@ApiImplicitParams:多个请求参数

2.SpringBoot中使用Swagger

2.1导入相关的依赖

注意:Swagger2和SpringBoot存在版本兼容的问题,选择的时候要根据SpringBoot的版本进行选择

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>

2.2创建配置类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket adminApiConfig(){

return new Docket(DocumentationType.SWAGGER_2)
.groupName("adminApi")
.apiInfo(apiInfo())
.select()
//只显示admin路径下的页面
.paths(Predicates.and(PathSelectors.regex("/admin/.*")))// .paths(PathSelectors.any())表示所有
.build();

}

private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("后台管理系统-API文档")
.description("本文档描述了后台管理系统微服务接口定义")
.version("1.0")
.contact(new Contact("GongChangjiang", "", "2602183349@qq.com"))
.build();
}

}

2.3配置包扫描的规则

1
2
//在项目的启动类加上该注解,swagger就会扫描如下包下的controller方法,生成接口文档
@ComponentScan(basePackages = "com.xxxx")

2.4使用接口文档

1
2
3
//浏览器访问该网址
//这里的端口号是要生成接口文档端口的端口号
http://localhost:8080/swagger-ui.html

image-20230412141010237