Spring MVC中使用Swagger生成API文档和完整项目示例Demo,swagger-server-api

来源:互联网 发布:java h5微信支付视频 编辑:程序博客网 时间:2024/04/30 00:25
实际项目中非常需要写文档,提高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关键配置

        
[html] view plain copy
  1. <dependency>  
  2.             <groupId>com.mangofactory</groupId>  
  3.             <artifactId>swagger-springmvc</artifactId>  
  4.             <version>1.0.2</version>  
  5.         </dependency>  
  6.   
  7.  <dependency>  
  8.         <groupId>org.springframework</groupId>  
  9.         <artifactId>spring-webmvc</artifactId>  
  10.         <version>4.1.6.RELEASE</version>  
  11.       </dependency>  


2. 插件配置
   CustomJavaPluginConfig

3.复制swagger的相关js等静态资源到webapp目录。
   swagger-ui.js之类的。
   我copy过一次,但是有问题,最后从网上下载了一个项目,可以直接用的那种。
   然后自己再逐步改造。

4.启动项目
   http://localhost:8080/



三、常见swagger注解一览与使用
最常用的5个注解

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

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

@ApiParam:单个参数描述


@ApiModel:用对象来接收参数

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


其它若干

@ApiResponse:HTTP响应其中1个描述

@ApiResponses:HTTP响应整体描述


@ApiClass

@ApiError

@ApiErrors


@ApiParamImplicit

@ApiParamsImplicit


四、关键代码和实际例子
    例子1:
   
[java] view plain copy
  1. @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)  
  2.     @ResponseBody  
  3.     @RequestMapping(value = "list", method = RequestMethod.POST)  
  4.     public Result<User> list(  
  5.             @ApiParam(value = "分类ID", required = true@RequestParam Long categoryId,  
  6.             @ApiParam(value = "token", required = true@RequestParam String token) {  
  7.         Result<User> result = new Result<User>();  
  8.         User user = new User();  
  9.         result.setData(user);  
  10.         return result;  
  11.     }  


   @ApiParam(value = "token", required = true) @RequestParam String token
Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。

  例子2:
[java] view plain copy
  1. @ApiOperation(value = "update用户", notes = ")", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)  
  2.   @ResponseBody  
  3.   @RequestMapping(value = "update", method = RequestMethod.GET/*,produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE*/)  
  4.   public Result<String> update(User user) {  
  5.       String u = findUser(user);  
  6.       System.out.println(u);  
  7.       return null;  
  8.   }  


 当参数太多的时候,需要定义太多的参数,排版看起来很不舒服。
这个时候,可以使用对象来接收。
@ApiModel(value = "用户对象",description="user2") 
public class User extends CommonParam{

}
Web前端/移动端HTTP请求方式:直接把参数附带到URL后面,或者用AJAX方法,表单提交。
这里面存在一个小问题,当后端用对象User来接收参数的时候,Swagger自带的工具是这样的:
 
这种形式,并不是表单提交,或者把参数附加到URL的后面。
我们只能手动构造URL,附带参数去提交。
如果需要测试的话!

例子3:
[java] view plain copy
  1. public Result<String> add(@RequestBody User user) {  
  2.     String u = findUser(user);  
  3.     System.out.println(u);  
  4.     return null;  
  5. }  


Web前端/移动端HTTP请求方式:必须把参数,放到request请求的body中去。
后端不能直接用request.getParam("token")这种。

获得request body中的数据,手动转换成目标数据。
    String charReader(HttpServletRequest request) throws IOException {

        BufferedReader br = request.getReader();

        String str, wholeStr = "";
        while ((str = br.readLine()) != null) {
            wholeStr += str;
        }
        return wholeStr;

    }

个人推荐
1.参数不多的时候,用例子1,用@ApiParam注解生成文档。
  swagger可视化界面,可以直接设置参数,发送请求来测试
2.参数比较多的时候,用例子2,用对象来接收参数,在对象里针对每个字段,@ApiModelProperty注解生成文档。
   swagger可视化界面,可以直接设置参数,但是无法接收到。
  因此,推荐使用其它HTTP请求或POST模拟工具,发送请求,模拟测试。

不推荐例子3,不通用,局限性比较大。


五、若干截图
 

六、源代码
[java] view plain copy
  1. package cn.fansunion.swagger.serverapi.controller;  
  2.   
  3. import org.springframework.http.MediaType;  
  4. import org.springframework.stereotype.Controller;  
  5. import org.springframework.web.bind.annotation.RequestBody;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.RequestMethod;  
  8. import org.springframework.web.bind.annotation.RequestParam;  
  9. import org.springframework.web.bind.annotation.ResponseBody;  
  10.   
  11. import com.wordnik.swagger.annotations.Api;  
  12. import com.wordnik.swagger.annotations.ApiOperation;  
  13. import com.wordnik.swagger.annotations.ApiParam;  
  14.   
  15. /** 
  16.  * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119 
  17.  * 博客:http://blog.csdn.net/fansunion 
  18.  * 
  19.  */  
  20. @Api(value = "user", description = "用户管理", produces = MediaType.APPLICATION_JSON_VALUE)  
  21. @Controller  
  22. @RequestMapping("user")  
  23. public class UserController {  
  24.   
  25.     // 列出某个类目的所有规格  
  26.     @ApiOperation(value = "获得用户列表", notes = "列表信息", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)  
  27.     @ResponseBody  
  28.     @RequestMapping(value = "list", method = RequestMethod.POST)  
  29.     public Result<User> list(  
  30.             @ApiParam(value = "分类ID", required = true@RequestParam Long categoryId,  
  31.             @ApiParam(value = "分类ID", required = true@RequestParam Long categoryId2,  
  32.             @ApiParam(value = "token", required = true@RequestParam String token) {  
  33.         Result<User> result = new Result<User>();  
  34.         User user = new User();  
  35.         result.setData(user);  
  36.         return result;  
  37.     }  
  38.   
  39.     @ApiOperation(value = "添加用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)  
  40.     @ResponseBody  
  41.     @RequestMapping(value = "add", method = RequestMethod.POST)  
  42.     // @RequestBody只能有1个  
  43.     // 使用了@RequestBody,不能在拦截器中,获得流中的数据,再json转换,拦截器中,也不清楚数据的类型,无法转换成java对象  
  44.     // 只能手动调用方法  
  45.     public Result<String> add(@RequestBody User user) {  
  46.         String u = findUser(user);  
  47.         System.out.println(u);  
  48.         return null;  
  49.     }  
  50.   
  51.     @ApiOperation(value = "update用户", notes = "获取商品信息(用于数据同步)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)  
  52.     @ResponseBody  
  53.     @RequestMapping(value = "update", method = RequestMethod.GET)  
  54.     public Result<String> update(User user) {  
  55.         String u = findUser(user);  
  56.         System.out.println(u);  
  57.         return null;  
  58.     }  
  59.   
  60.     private String findUser(User user) {  
  61.         String token = user.getToken();  
  62.         return token;  
  63.     }  
  64. }  


[java] view plain copy
  1. package cn.fansunion.swagger.serverapi.controller;  
  2.   
  3. import com.wordnik.swagger.annotations.ApiModel;  
  4. import com.wordnik.swagger.annotations.ApiModelProperty;  
  5.   
  6. /** 
  7.  * 小雷FansUnion-一个有创业和投资经验的资深程序员-全球最大中文IT社区CSDN知名博主-排名第119 
  8.  * 博客:http://blog.csdn.net/fansunion 
  9.  * 
  10.  */  
  11. @ApiModel(value = "用户对象", description = "user2")  
  12. public class User extends CommonParam {  
  13.   
  14.     @ApiModelProperty(value = "商品信息", required = true)  
  15.     private String name;  
  16.     @ApiModelProperty(value = "密码", required = true)  
  17.     private String password;  
  18.   
  19.     @ApiModelProperty(value = "性别")  
  20.     private Integer sex;  
  21.     @ApiModelProperty(value = "密码", required = true)  
  22.     private String token;  
  23.   
  24.     public String getToken() {  
  25.         return token;  
  26.     }  
  27.   
  28.     public void setToken(String token) {  
  29.         this.token = token;  
  30.     }  
  31.   
  32.     public String getName() {  
  33.         return name;  
  34.     }  
  35.   
  36.     public void setName(String name) {  
  37.         this.name = name;  
  38.     }  
  39.   
  40.     public String getPassword() {  
  41.         return password;  
  42.     }  
  43.   
  44.     public void setPassword(String password) {  
  45.         this.password = password;  
  46.     }  
  47.   
  48.     public Integer getSex() {  
  49.         return sex;  
  50.     }  
  51.   
  52.     public void setSex(Integer sex) {  
  53.         this.sex = sex;  
  54.     }  
  55.   
  56. }  

[java] view plain copy
  1. package cn.fansunion.swagger.serverapi.swagger;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.context.annotation.Bean;  
  5. import org.springframework.context.annotation.Configuration;  
  6. import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;  
  7. import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
  8. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  9.   
  10. import com.mangofactory.swagger.configuration.SpringSwaggerConfig;  
  11. import com.mangofactory.swagger.models.dto.ApiInfo;  
  12. import com.mangofactory.swagger.paths.SwaggerPathProvider;  
  13. import com.mangofactory.swagger.plugin.EnableSwagger;  
  14. import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;  
  15.   
  16. @Configuration  
  17. @EnableWebMvc  
  18. @EnableSwagger  
  19. public class CustomJavaPluginConfig extends WebMvcConfigurerAdapter {  
  20.   
  21.     private SpringSwaggerConfig springSwaggerConfig;  
  22.   
  23.     @Autowired  
  24.     public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {  
  25.         this.springSwaggerConfig = springSwaggerConfig;  
  26.     }  
  27.   
  28.     /** 
  29.      * 链式编程 来定制API样式 后续会加上分组信息 
  30.      *  
  31.      * @return 
  32.      */  
  33.     @Bean  
  34.     public SwaggerSpringMvcPlugin customImplementation() {  
  35.         return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)  
  36.                 .apiInfo(apiInfo()).includePatterns(".*")  
  37.                 .useDefaultResponseMessages(false)  
  38.             //  .pathProvider(new GtPaths())  
  39.                 .apiVersion("0.1").swaggerGroup("user");  
  40.   
  41.     }  
  42.   
  43.     private ApiInfo apiInfo() {  
  44.         ApiInfo apiInfo = new ApiInfo("小雷移动端API接口平台",  
  45.                 "提供详细的后台所有Restful接口""http://blog.csdn.net/FansUnion",  
  46.                 "FansUnion@qq.com""小雷博客""http://blog.csdn.net/FansUnion");  
  47.         return apiInfo;  
  48.     }  
  49.   
  50.     @Override  
  51.     public void configureDefaultServletHandling(  
  52.             DefaultServletHandlerConfigurer configurer) {  
  53.         configurer.enable();  
  54.     }  
  55.   
  56.     class GtPaths extends SwaggerPathProvider {  
  57.   
  58.         @Override  
  59.         protected String applicationPath() {  
  60.             return "/restapi";  
  61.         }  
  62.   
  63.         @Override  
  64.         protected String getDocumentationPath() {  
  65.             return "/restapi";  
  66.         }  
  67.     }  
  68.   
  69. }  

七、项目下载地址
  http://git.oschina.net/fansunion/swagger-server-api/tree/master/

八、参考资料
http://blog.csdn.net/jia20003/article/details/50700736
http://www.cnblogs.com/quanyongan/archive/2013/04/16/3024741.html
http://www.cnblogs.com/h9527/p/5506956.html
http://www.cnblogs.com/yuananyun/p/4993426.html
阅读全文
0 0
原创粉丝点击