Swagger2构建RestFul API文档
由于 Spring Boot 能够快速开发、便捷部署等特性, 通常在使用 Spring Boot
构建 Restful 接口应用时考虑到多终端的原因,这些终端会共用很多底层业务
逻辑,因此我们会抽象出这样一层来同时服务于多个移动端或者 Web 前端。 对于
不同的终端公用一套接口 Api 时对于联调测试时就需要知道后端提供的接口
Api 列表文档,对于服务端开发人员来说就需要编写接口文档,描述接口调用地
址 参数 结果等,这里借助第三方构建工具Swagger2来实现Api文档生成功能。
实现步骤:
1.pom.xml 文件修改,加入 swagger2 坐标依赖
<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>
2.接口方法引入 swagger2 注解声明
方法级别声明@ApiOperation 注解,声明当前接口实现业务功
能,@ApiImplicitParam 标注当前接口方法参数相关声明
@RestController
public class UserController02 {
@Resource
private UserService userService;
@ApiOperation("根据id查找用户") //方法说明,在api文档中可看
@RequestMapping(value = "user/{id}",method= RequestMethod.GET)
public User queryUserById(@PathVariable Integer id){
return userService.queryUserById(id);
}
}
3.Swagger2 配置文件添加
@Configuration
@EnableSwagger2 //声明该类为Swagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.shsxt.control
ler"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户模块管理接口 API 文档参考")
.contact("上海尚学堂")
.version("1.0")
.build();
}
}
4.启动项目并访问接口 api 地址 http://localhost:8989/swagger-ui.html
通过 html 页面形式告诉终端调用者接口地址以及相关接口调用参数传入类
型,极大方便前后端分离开发联调工作。