Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档

2023-07-29,,

1、添加Swagger2依赖

在pom.xml中加入Swagger2的依赖

<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>

2

编写Swagger2配置类

/**
* ${DESCRIPTION}
*
* @author Ricky Fung
* @create 2017-01-02 23:53
*/
@EnableSwagger2
@Configuration
public class Swagger2Config { @Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.bytebeats.springboot.ch2.controller"))
.paths(PathSelectors.any())
.build();
}
//构建 api文档的详细信息函数
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot 测试使用 Swagger2 构建RESTful API")
//创建人
.contact(new Contact("Ricky", "http://www.bytebeats.com", "ricky_feng@163.com"))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build();
}
}

3、编写Controller

这里开始编写自己的RESTful Controller,跟正常开发没什么区别。主要是接口方法上面新增了几个注解:

通过@ApiOperation注解来给API增加说明
通过@ApiImplicitParams、@ApiImplicitParam注解来给参数增加说明
通过@ApiIgnore来忽略那些不想让生成RESTful API文档的接口

4 完成上述代码后,打包Spring Boot程序并启动,打开浏览器访问:http://localhost:8080/swagger-ui.html,就能看到前文所展示的RESTful API的页面。

5、Swagger常用注解:

@Api 标识Controller使用swagger.
@ApiImplicitParam 表示一个隐式的请求参数,即请求方法中没有显示绑定参数名称.
@ApiImplicitParams 表示隐式参数列表.
@ApiModel 描述请求或返回对象的额外信息.
@ApiModelProperty 描述或者生成ApiModel的成员变量.
@ApiOperation 描述一个Http请求方法
@ApiParam 描述显示的请求参数.
@ApiResponse 描述可能的返回对象.
@ApiResponses 表示返回对象列表.
@Authorization 申明认证信息.
@ResponseHeader 表示返回头部信息.

github:https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#api

Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档的相关教程结束。

《Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档.doc》

下载本文的Word格式文档,以方便收藏与打印。