实际项目中非常需要写文档,提高Java服务端和Web前端以及移动端的对接效率。
听说Swagger这个工具,还不错,就网上找了些资料,自己实践了下。
一:Swagger介绍
Swagger是当前最好用的Restful API文档生成的开源项目,通过swagger-spring项目
实现了与SpingMVC框架的无缝集成功能,方便生成spring restful风格的接口文档,
同时swagger-ui还可以测试spring restful风格的接口功能。
官方网站为:http://swagger.io/
中文网站:
http://www.sosoapi.com
二:Swagger与Spring MVC集成步骤
1.Maven关键配置
<dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.6.RELEASE</version> </dependency>
2. 插件配置
CustomJavaPluginConfig
3.复制swagger的相关js等静态资源到webapp目录。
swagger-ui.js之类的。
我copy过一次,但是有问题,最后从网上下载了一个项目,可以直接用的那种。
然后自己再逐步改造。
4.启动项目
![](https://i-blog.csdnimg.cn/blog_migrate/78e7b48ff4cf3e173900de995e23bab5.png)
三、常见swagger注解一览与使用
最常用的5个注解
@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiProperty:用对象接收参数时,描述对象的一个字段
其它若干
@ApiResponse:HTTP响应其中1个描述
@ApiResponses:HTTP响应整体描述
@ApiClass
@ApiError
@ApiErrors
@ApiParamImplicit
@ApiParamsImplicit
四、关键代码和实际例子
例子1:
@ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @RequestMapping(value = "list", method = RequestMethod.POST) public Result<User> list( @ApiParam(value = "分类ID", required = true) @RequestParam Long categoryId, @ApiParam