SwaggerUI+SpringMVC——构建RestFulAPI的可视化界面

来源:互联网 发布:淘宝官方网站下载 编辑:程序博客网 时间:2024/05/02 18:19
今天给大家介绍一款工具,这个工具目前可预见的好处是:自动维护最新的接口文档。
我们都知道,接口文档是非常重要的,但是随着代码的不断更新,文档却很难持续跟着更新,今天要介绍的工具,完美的解决了这个问题。而且,对于要使用我们接口的人来说,不需要在给他提供文档,告诉他地址,一目了然。
最近项目中一直有跟接口打交道,恰好又接触到了一个新的接口工具,拿出来跟大家分享一下。
关于REST接口,我在上篇文章中已经有介绍,这里来说一下如何配合SwaggerUI搭建RestFul API 的可视化界面。最终要达到的效果是这样的:
它可以支持Rest的所有提交方式,如POST,GET,PUT,DELETE等。
这里可以看到我们的方法注释,需要的参数,参数的类型和注释,返回值的类型注释等信息,最重要的,我们这里可以直接对REST接口测试。
接下来,我们一起开始逐步实现如图的效果
第一步:首先,引入依赖的jar包
[html] view plain copy
 print?
  1. <span style="white-space:pre">    </span><!-- swagger -->  
  2.     <dependency>  
  3.         <groupId>com.mangofactory</groupId>  
  4.         <artifactId>swagger-springmvc</artifactId>  
  5.         <version>0.9.5</version>  
  6.     </dependency>  
  7.     <dependency>  
  8.             <groupId>com.fasterxml.jackson.core</groupId>  
  9.             <artifactId>jackson-annotations</artifactId>  
  10.             <version>2.4.4</version>  
  11.         </dependency>  
  12.         <dependency>  
  13.             <groupId>com.fasterxml.jackson.core</groupId>  
  14.             <artifactId>jackson-databind</artifactId>  
  15.             <version>2.4.4</version>  
  16.         </dependency>  
  17.         <dependency>  
  18.             <groupId>com.fasterxml.jackson.core</groupId>  
  19.             <artifactId>jackson-core</artifactId>  
  20.             <version>2.4.4</version>  
  21.         </dependency>  
第二步,创建swagger配置文件类,基本不用改,只需要修改要匹配的方法路径即可。
[java] view plain copy
 print?
  1. package com.gochina.mis.util;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.context.annotation.Bean;  
  5. import org.springframework.context.annotation.ComponentScan;  
  6. import org.springframework.context.annotation.Configuration;  
  7.   
  8. import com.mangofactory.swagger.configuration.SpringSwaggerConfig;  
  9. import com.mangofactory.swagger.models.dto.ApiInfo;  
  10. import com.mangofactory.swagger.plugin.EnableSwagger;  
  11. import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;  
  12.   
  13. @Configuration  
  14. @EnableSwagger  
  15. public class SwaggerConfig {  
  16.   
  17.     private SpringSwaggerConfig springSwaggerConfig;  
  18.   
  19.     @Autowired  
  20.     public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {  
  21.         this.springSwaggerConfig = springSwaggerConfig;  
  22.     }  
  23.   
  24.     @Bean  
  25.     public SwaggerSpringMvcPlugin customImplementation()  
  26.     {  
[java] view plain copy
 print?
  1.         return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns("/album/*");//这里是支持正则匹配的,只有这里配置了才可以在页面看到。  
  2.     }  
  3.   
  4.     private ApiInfo apiInfo() {  
  5.         ApiInfo apiInfo = new ApiInfo(null,null,null,null,null,null);  
  6.         return apiInfo;  
  7.     }  
  8. }  
第三步:把配置文件类加入spring容器
[html] view plain copy
 print?
  1. <span style="white-space:pre">    </span><!--swagger-->  
  2.     <bean class="com.gochina.mis.util.SwaggerConfig"/>  
到这里,我们后台的环境代码就完成了,接着,添加SwaggerUI提供的js界面
下载swagger-ui
https://github.com/swagger-api/swagger-ui
将dist下的文件放入webapp下
配置mvc:resource,防止spring拦截。
[html] view plain copy
 print?
  1. <span style="white-space:pre">        </span><mvc:resources mapping="/api-doc/**" location="/api-doc/" />  
将index.html中的
http://petstore.swagger.wordnik.com/v2/swagger.json
修改为http://localhost:8080/{projectname}/api-docs

到此,完成了所有的基本配置,接下来,需要对每个接口添加注解。
下面来个实例
接口类
[java] view plain copy
 print?
  1. package com.gochina.mis.api;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.beans.BeanUtils;  
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.stereotype.Controller;  
  8. import org.springframework.web.bind.annotation.ModelAttribute;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.ResponseBody;  
  12.   
  13. import com.gochina.mis.bean.Album;  
  14. import com.gochina.mis.bean.ResultPo;  
  15. import com.gochina.mis.service.AlbumService;  
  16. import com.gochina.mis.util.JsonUtil;  
  17. import com.gochina.mis.util.StringUtil;  
  18. import com.gochina.mis.vo.BaseVo;  
  19. import com.gochina.mis.vo.RequestAlbumVo;  
  20. import com.wordnik.swagger.annotations.Api;  
  21. import com.wordnik.swagger.annotations.ApiOperation;  
  22.   
  23. @Controller  
  24. public class AlbumAction {  
  25.     private static Logger logger = LoggerFactory.getLogger(AlbumAction.class);  
  26.       
  27.     @Autowired  
  28.     private AlbumService albumService;  
  29.       
  30.     @ResponseBody  
  31.     @RequestMapping(value="album", method = RequestMethod.POST,produces = "application/json;charset=utf-8")  
  32.     @ApiOperation(value="第三方添加专辑", httpMethod ="POST", response=BaseVo.class, notes ="第三方添加专辑")  
  33.     public String postAlbum(@ModelAttribute("requestAlbumVo")RequestAlbumVo requestAlbumVo){  
  34.         BaseVo result = new BaseVo();  
  35.         Album album = new Album();  
  36.         if (requestAlbumVo!=null) {  
  37.             logger.info("传入参数:requestAlbumVo:{}",JsonUtil.beanToJson(requestAlbumVo));  
  38.             try {  
  39.                 BeanUtils.copyProperties(requestAlbumVo, album);  
  40.                 result=albumService.save(album);  
  41.             } catch (Exception e) {  
  42.                 e.printStackTrace();  
  43.                 result.setSuccess(false);  
  44.                 result.setMsg("添加专辑失败!");  
  45.                 logger.error("添加专辑失败传入参数:requestAlbumVo:{},错误信息为:{}",JsonUtil.beanToJson(requestAlbumVo),e.getMessage());  
  46.             }  
  47.         }else {  
  48.             result.setSuccess(false);  
  49.             result.setMsg("参数不合法!");  
  50.         }  
  51.         logger.info("传入参数:requestAlbumVo:{},返回结果为:{}",JsonUtil.beanToJson(requestAlbumVo),JsonUtil.beanToJson(result));  
  52.         return JsonUtil.beanToJson(result);  
  53.     }  
  54. }  
我们可以看到,这里使用SpringMVC,请求参数传入的是实体类,对于传入参数的注解,就放到了实体中
请求参数实体
[java] view plain copy
 print?
  1. package com.gochina.mis.vo;  
  2.   
  3. import com.wordnik.swagger.annotations.ApiModelProperty;  
  4.   
  5. public class RequestAlbumVo {  
  6.       
  7.     @ApiModelProperty(value = "专辑名称", required = true)  
  8.     private String name;  
  9.       
  10.     @ApiModelProperty(value = "第三方专辑Id", required = true)  
  11.     private String thirdAlbumId;//第三方专辑Id  
  12.       
  13.     @ApiModelProperty(value = "第三方专辑Id", required = true)  
  14.     private String thirdSystemId;//第三方系统Id  
  15.       
  16.     @ApiModelProperty(value = "标准图", required = false)  
  17.     private String standardPic;//标准图  
  18.       
  19.     @ApiModelProperty(value = "竖图", required = false)  
  20.     private String ystandardPic;//竖图  
  21.       
  22.     @ApiModelProperty(value = "水印图片", required = false)    
  23.     private String markPic;//水印图片  
  24.       
  25.     @ApiModelProperty(value = "水印图片位置", required = false)  
  26.     private String markPosition;//水印图片位置  
  27.       
  28.     @ApiModelProperty(value = "标签", required = false)  
  29.     private String tag;//标签  
  30.       
  31.     @ApiModelProperty(value = "评分", required = false)  
  32.     private String score;//评分  
  33.       
  34.     @ApiModelProperty(value = "描述", required = false)  
  35.     private String description;//描述  
  36.   
  37.     public String getName() {  
  38.         return name;  
  39.     }  
  40.   
  41.     public void setName(String name) {  
  42.         this.name = name;  
  43.     }  
  44.   
  45.     public String getThirdAlbumId() {  
  46.         return thirdAlbumId;  
  47.     }  
  48.   
  49.     public void setThirdAlbumId(String thirdAlbumId) {  
  50.         this.thirdAlbumId = thirdAlbumId;  
  51.     }  
  52.   
  53.     public String getThirdSystemId() {  
  54.         return thirdSystemId;  
  55.     }  
  56.   
  57.     public void setThirdSystemId(String thirdSystemId) {  
  58.         this.thirdSystemId = thirdSystemId;  
  59.     }  
  60.   
  61.     public String getStandardPic() {  
  62.         return standardPic;  
  63.     }  
  64.   
  65.     public void setStandardPic(String standardPic) {  
  66.         this.standardPic = standardPic;  
  67.     }  
  68.   
  69.     public String getYstandardPic() {  
  70.         return ystandardPic;  
  71.     }  
  72.   
  73.     public void setYstandardPic(String ystandardPic) {  
  74.         this.ystandardPic = ystandardPic;  
  75.     }  
  76.   
  77.     public String getMarkPic() {  
  78.         return markPic;  
  79.     }  
  80.   
  81.     public void setMarkPic(String markPic) {  
  82.         this.markPic = markPic;  
  83.     }  
  84.   
  85.     public String getMarkPosition() {  
  86.         return markPosition;  
  87.     }  
  88.   
  89.     public void setMarkPosition(String markPosition) {  
  90.         this.markPosition = markPosition;  
  91.     }  
  92.   
  93.     public String getTag() {  
  94.         return tag;  
  95.     }  
  96.   
  97.     public void setTag(String tag) {  
  98.         this.tag = tag;  
  99.     }  
  100.   
  101.     public String getScore() {  
  102.         return score;  
  103.     }  
  104.   
  105.     public void setScore(String score) {  
  106.         this.score = score;  
  107.     }  
  108.   
  109.     public String getDescription() {  
  110.         return description;  
  111.     }  
  112.   
  113.     public void setDescription(String description) {  
  114.         this.description = description;  
  115.     }  
  116.       
  117. }  
返回参数,这里也是用的实体
[java] view plain copy
 print?
  1. package com.gochina.mis.vo;  
  2.   
  3. import java.sql.Timestamp;  
  4. import com.wordnik.swagger.annotations.ApiModelProperty;  
  5.   
  6. /** 
  7.  * 返回信息 
  8.  * @author LBQ-PC 
  9.  * 
  10.  */  
  11. public class BaseVo {  
  12.   
  13.     /** 
  14.      * 状态 
  15.      */  
  16.     @ApiModelProperty(value = "状态")   
  17.     private Boolean success;  
  18.       
  19.     /** 
  20.      * 消息 
  21.      */  
  22.     @ApiModelProperty(value = "消息")  
  23.     private String msg;  
  24.       
  25.     /** 
  26.      * 服务器当前时间 
  27.      */  
  28.     @ApiModelProperty(value = "服务器当前时间戳,sample: 1434553831")  
  29.     private Long currentTime = new Timestamp(System.currentTimeMillis()).getTime();  
  30.   
  31.     public Boolean getSuccess() {  
  32.         return success;  
  33.     }  
  34.   
  35.     public void setSuccess(Boolean success) {  
  36.         this.success = success;  
  37.     }  
  38.   
  39.     public String getMsg() {  
  40.         return msg;  
  41.     }  
  42.   
  43.     public void setMsg(String message) {  
  44.         this.msg = message;  
  45.     }  
  46.   
  47.     public Long getCurrentTime() {  
  48.         return currentTime;  
  49.     }  
  50.   
  51.     public void setCurrentTime(Long currentTime) {  
  52.         this.currentTime = currentTime;  
  53.     }  
  54.   
  55.   
  56. }  
运行访问:http://localhost:8080/api-doc/index.html ,当然,我们也可以对这个页面加权限验证

大功告成!对于开发人员来说,每个接口只需要添加一些注解,SwaggerUI会自动生成如我们文章开始时展现的页面,方便调用和测试。

转自:http://blog.csdn.net/libaoqiang613/article/details/47398715

0 0