今天给大家介绍一款工具,这个工具眼下可预见的优点是:自己主动维护最新的接口文档。

我们都知道,接口文档是非常重要的,可是随着代码的不断更新,文档却非常难持续跟着更新,今天要介绍的工具,完美的攻克了这个问题。

并且。对于要使用我们接口的人来说,不须要在给他提供文档,告诉他地址。一目了然。

近期项目中一直有跟接口打交道,恰好又接触到了一个新的接口工具,拿出来跟大家分享一下。

关于REST接口,我在上篇文章中已经有介绍。这里来说一下怎样配合SwaggerUI搭建RestFul API 的可视化界面。终于要达到的效果是这种:
它能够支持Rest的全部提交方式,如POST,GET,PUT,DELETE等。
这里能够看到我们的方法凝视,须要的參数。參数的类型和凝视。返回值的类型凝视等信息,最重要的,我们这里能够直接对REST接口測试。

接下来。我们一起開始逐步实现如图的效果
第一步:首先。引入依赖的jar包
<span style="white-space:pre">	</span><!-- swagger -->
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>0.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.4</version>
</dependency>

第二步,创建swagger配置文件类。基本不用改,仅仅须要改动要匹配的方法路径就可以。

package com.gochina.mis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
import com.mangofactory.swagger.models.dto.ApiInfo;
import com.mangofactory.swagger.plugin.EnableSwagger;
import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; @Configuration
@EnableSwagger
public class SwaggerConfig { private SpringSwaggerConfig springSwaggerConfig; @Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
} @Bean
public SwaggerSpringMvcPlugin customImplementation()
{
        return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(apiInfo()).includePatterns("/album/*");//这里是支持正则匹配的。仅仅有这里配置了才干够在页面看到。
} private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(null,null,null,null,null,null);
return apiInfo;
}
}

第三步:把配置文件类增加spring容器

<span style="white-space:pre">	</span><!--swagger-->
<bean class="com.gochina.mis.util.SwaggerConfig"/>

到这里,我们后台的环境代码就完毕了,接着,加入SwaggerUI提供的js界面

下载swagger-ui

https://github.com/swagger-api/swagger-ui

将dist下的文件放入webapp下

配置mvc:resource。防止spring拦截。
<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

到此,完毕了全部的基本配置,接下来,须要对每一个接口加入注解。
以下来个实例
接口类
package com.gochina.mis.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import com.gochina.mis.bean.Album;
import com.gochina.mis.bean.ResultPo;
import com.gochina.mis.service.AlbumService;
import com.gochina.mis.util.JsonUtil;
import com.gochina.mis.util.StringUtil;
import com.gochina.mis.vo.BaseVo;
import com.gochina.mis.vo.RequestAlbumVo;
import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation; @Controller
public class AlbumAction {
private static Logger logger = LoggerFactory.getLogger(AlbumAction.class); @Autowired
private AlbumService albumService; @ResponseBody
@RequestMapping(value="album", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
@ApiOperation(value="第三方加入专辑", httpMethod ="POST", response=BaseVo.class, notes ="第三方加入专辑")
public String postAlbum(@ModelAttribute("requestAlbumVo")RequestAlbumVo requestAlbumVo){
BaseVo result = new BaseVo();
Album album = new Album();
if (requestAlbumVo!=null) {
logger.info("传入參数:requestAlbumVo:{}",JsonUtil.beanToJson(requestAlbumVo));
try {
BeanUtils.copyProperties(requestAlbumVo, album);
result=albumService.save(album);
} catch (Exception e) {
e.printStackTrace();
result.setSuccess(false);
result.setMsg("加入专辑失败! ");
logger.error("加入专辑失败传入參数:requestAlbumVo:{},错误信息为:{}",JsonUtil.beanToJson(requestAlbumVo),e.getMessage());
}
}else {
result.setSuccess(false);
result.setMsg("參数不合法!");
}
logger.info("传入參数:requestAlbumVo:{},返回结果为:{}",JsonUtil.beanToJson(requestAlbumVo),JsonUtil.beanToJson(result));
return JsonUtil.beanToJson(result);
}
}

我们能够看到,这里使用SpringMVC,请求參数传入的是实体类。对于传入參数的注解,就放到了实体中

请求參数实体
package com.gochina.mis.vo;

import com.wordnik.swagger.annotations.ApiModelProperty;

public class RequestAlbumVo {

	@ApiModelProperty(value = "专辑名称", required = true)
private String name; @ApiModelProperty(value = "第三方专辑Id", required = true)
private String thirdAlbumId;//第三方专辑Id @ApiModelProperty(value = "第三方专辑Id", required = true)
private String thirdSystemId;//第三方系统Id @ApiModelProperty(value = "标准图", required = false)
private String standardPic;//标准图 @ApiModelProperty(value = "竖图", required = false)
private String ystandardPic;//竖图 @ApiModelProperty(value = "水印图片", required = false)
private String markPic;//水印图片 @ApiModelProperty(value = "水印图片位置", required = false)
private String markPosition;//水印图片位置 @ApiModelProperty(value = "标签", required = false)
private String tag;//标签 @ApiModelProperty(value = "评分", required = false)
private String score;//评分 @ApiModelProperty(value = "描写叙述", required = false)
private String description;//描写叙述 public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getThirdAlbumId() {
return thirdAlbumId;
} public void setThirdAlbumId(String thirdAlbumId) {
this.thirdAlbumId = thirdAlbumId;
} public String getThirdSystemId() {
return thirdSystemId;
} public void setThirdSystemId(String thirdSystemId) {
this.thirdSystemId = thirdSystemId;
} public String getStandardPic() {
return standardPic;
} public void setStandardPic(String standardPic) {
this.standardPic = standardPic;
} public String getYstandardPic() {
return ystandardPic;
} public void setYstandardPic(String ystandardPic) {
this.ystandardPic = ystandardPic;
} public String getMarkPic() {
return markPic;
} public void setMarkPic(String markPic) {
this.markPic = markPic;
} public String getMarkPosition() {
return markPosition;
} public void setMarkPosition(String markPosition) {
this.markPosition = markPosition;
} public String getTag() {
return tag;
} public void setTag(String tag) {
this.tag = tag;
} public String getScore() {
return score;
} public void setScore(String score) {
this.score = score;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} }

返回參数。这里也是用的实体

package com.gochina.mis.vo;

import java.sql.Timestamp;
import com.wordnik.swagger.annotations.ApiModelProperty; /**
* 返回信息
* @author LBQ-PC
*
*/
public class BaseVo { /**
* 状态
*/
@ApiModelProperty(value = "状态")
private Boolean success; /**
* 消息
*/
@ApiModelProperty(value = "消息")
private String msg; /**
* server当前时间
*/
@ApiModelProperty(value = "server当前时间戳,sample: 1434553831")
private Long currentTime = new Timestamp(System.currentTimeMillis()).getTime(); public Boolean getSuccess() {
return success;
} public void setSuccess(Boolean success) {
this.success = success;
} public String getMsg() {
return msg;
} public void setMsg(String message) {
this.msg = message;
} public Long getCurrentTime() {
return currentTime;
} public void setCurrentTime(Long currentTime) {
this.currentTime = currentTime;
} }

执行訪问:http://localhost:8080/api-doc/index.html ,当然,我们也能够对这个页面加权限验证


大功告成!对于开发者来说,每一个接口仅仅须要加入一些注解,SwaggerUI会自己主动生成如我们文章開始时展现的页面,方便调用和測试。


SwaggerUI+SpringMVC——构建RestFul API的可视化界面的更多相关文章

  1. 集成swagger2构建Restful API

    集成swagger2构建Restful API 在pom.xml中进行版本管理 <swagger.version>2.8.0</swagger.version> 给taosir ...

  2. Spring Boot 入门系列(二十二)使用Swagger2构建 RESTful API文档

    前面介绍了如何Spring Boot 快速打造Restful API 接口,也介绍了如何优雅的实现 Api 版本控制,不清楚的可以看我之前的文章:https://www.cnblogs.com/zha ...

  3. Spring MVC中使用 Swagger2 构建Restful API

    1.Spring MVC配置文件中的配置 [java] view plain copy <!-- 设置使用注解的类所在的jar包,只加载controller类 --> <contex ...

  4. Springboot 如何加密,以及利用Swagger2构建Restful API

    先看一下使用Swagger2构建Restful API效果图 超级简单的,只需要在pom 中引用如下jar包 <dependency> <groupId>io.springfo ...

  5. springboot集成swagger2构建RESTful API文档

    在开发过程中,有时候我们需要不停的测试接口,自测,或者交由测试测试接口,我们需要构建一个文档,都是单独写,太麻烦了,现在使用springboot集成swagger2来构建RESTful API文档,可 ...

  6. 使用ASP.NET Core 3.x 构建 RESTful API - 2. 什么是RESTful API

    1. 使用ASP.NET Core 3.x 构建 RESTful API - 1.准备工作 什么是REST REST一词最早是在2000年,由Roy Fielding在他的博士论文<Archit ...

  7. 使用ASP.NET Core构建RESTful API的技术指南

    译者荐语:利用周末的时间,本人拜读了长沙.NET技术社区翻译的技术标准<微软RESTFul API指南>,打算按照步骤写一个完整的教程,后来无意中看到了这篇文章,与我要写的主题有不少相似之 ...

  8. 使用Express构建RESTful API

    RESTful服务 REST(Representational State Transfer)的意思是表征状态转移,它是一种基于HTTP协议的网络应用接口风格,充分利用HTTP的方法实现统一风格接口的 ...

  9. SpringBoot 构建RestFul API 含单元测试

    相关博文: 从消费者角度评估RestFul的意义 SpringBoot 构建RestFul API 含单元测试 首先,回顾并详细说明一下在快速入门中使用的  @Controller .  @RestC ...

随机推荐

  1. 在Win7环境下安装启动Linux

    在Win7环境下安装启动Linux 在Win7系统下,安装启动Linux特别的不方便,由于XP下的boot.ini配置文件不在了,要加入�一下启动选项的话, 仅仅能使用专门的工具,这或多或少给人带来不 ...

  2. [转载] 为Visual Studio添加默认INCLUDE包含路径的方法

    原文地址 你是否曾经也有过这样的问题: 用VS的时候,有时会用到一些非自带的库,例如WTL.Boost.DX等,每次需要用到时都要在项目属性里添加相应的include目录,久而久之觉得有点麻烦.是否有 ...

  3. 聊聊JVM的年轻代(转)

    聊聊JVM的年轻代 本文转自http://ifeve.com/jvm-yong-generation/ 1.为什么会有年轻代 我们先来屡屡,为什么需要把堆分代?不分代不能完成他所做的事情么?其实不分代 ...

  4. linux列出一个目录及其子目录下面的某种类型的文件

    linux列出一个目录及其子目录下面的某种类型的文件 作者:smarteng ⁄ 时间:2009年07月09日 ⁄ 分类: Linux命令 ⁄ 评论:0 怎么样把,一个目录及其所有的子目录下面的某种类 ...

  5. 《Head First 设计模式》学习笔记——策略模型

    我们全都使用别人设计好的库与框架.我们讨论库与框架.利用他们的API编译成我们的程序.享受运用别人的代码所带来的长处.看看java api它所带来的功能:网络.GUI.IO等.库与框架长久以来,一直扮 ...

  6. 怎么上传自己的代码/项目到自己的github仓库上

    创建新的git仓库   设置新仓库   创建完成后   复制git地址   现在已经有window git客户端了(地址:https://desktop.github.com/),但还是建议用git命 ...

  7. HDU1226:超级密码(BFS)

    Problem Description Ignatius花了一个星期的时间终于找到了传说中的宝藏,宝藏被放在一个房间里,房间的门用密码锁起来了,在门旁边的墙上有一些关于密码的提示信息: 密码是一个C进 ...

  8. Python爬虫之selenium爬虫,模拟浏览器爬取天猫信息

    由于工作需要,需要提取到天猫400个指定商品页面中指定的信息,于是有了这个爬虫.这是一个使用 selenium 爬取天猫商品信息的爬虫,虽然功能单一,但是也算是 selenium 爬虫的基本用法了. ...

  9. Longest Valid Parentheses leetcode java

    题目: Given a string containing just the characters '(' and ')', find the length of the longest valid ...

  10. java代码在开始事务后,先做了一个查询,再insert,此时会报: java.sql.SQLException: could not retrieve transation read-only status server

    解决过程: 查看mysql的事物隔离级别 SHOW VARIABLES LIKE '%iso%'; 返回结果: REPEATABLE-READ 把这个改成:READ-COMMITTED 就好了: SE ...