版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qincidong/article/details/76118201
springboot利用swagger构建api文档
前言
Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。本文简单介绍了在项目中集成swagger的方法。
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
使用
1.添加swagger依赖
<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.添加swagger配置
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.ybf.activity.web.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restful风格,http://luckystar88.github.io/")
.termsOfServiceUrl("http://luckystar88.github.io/")
.version("1.0")
.build();
}
}
注意spring boot的包结构,否则会导致配置无效。示例程序的包结构:
com.ybf.activity.web|
———————-|config
—————————–Swagger2.java
———————-Application.java
3.在接口方法上使用注解添加描述信息
@ApiOperation(value = "用户某个用户的信息",notes = "根据用户id获取用户详细信息")
@ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "int",paramType = "path")
@RequestMapping(value = "/student/{id}",method = RequestMethod.GET)
@ResponseBody
public Student student(@PathVariable int id) {
return studentMapper.getById(id);
}
@ApiOperation(value = "获取用户信息(分页)",notes = "根据传入的页数获取用户信息")
@ApiImplicitParam(name="pageNo",value = "页数",required = true,dataType = "int",paramType = "path")
@RequestMapping(value = "/student/page/{pageNo}",method = RequestMethod.GET)
@ResponseBody
public List<Student> selectStudentByPage(@PathVariable int pageNo) {
if (pageNo > 0) {
PageHelper.startPage(pageNo,3); // 设置分页,参数1=页数,参数2=每页显示条数
}
return studentMapper.sel();
}
默认会对所有的方法生成API文档,如果某个方法不需要,可以添加@ApiIgnore。
启动SpringBoot程序,浏览器输入:项目上下文路径/swagger-ui.html就可以看到效果。
点击某个请求,可以查看详情:
输入参数,点击Try it out按钮可以查看响应。