springmvc使用swagger生成rest api文档
pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
ApiConfig.java
package com.geostar.gfstack.operationcenter.core.common.util; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration //必须存在
@EnableSwagger2 //必须存在
@EnableWebMvc //必须存在
public class ApiConfig { @Bean
public Docket customDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(GeoRequestHandlerSelectors.basePackage("com.geostar.gfstack.operationcenter.cloudform.action"))
.paths(PathSelectors.any())
.build()
.useDefaultResponseMessages(false);
} private ApiInfo apiInfo() {
Contact contact = new Contact("武大吉奥", "http://www.geostar.com.cn/", "techsupport@geostar.com.cn");
return new ApiInfo("综合运维管理系统API接口",//大标题 title
"综合运维管理系统API接口",//小标题
"1.8.2.0",//版本
"http://www.geostar.com.cn/",//termsOfServiceUrl
contact,//作者
"武大吉奥",//链接显示文字
"http://www.geostar.com.cn/"//网站链接
);
} }
确保ApiConfig在spring扫描范围内
GeoRequestHandlerSelectors.java
package com.geostar.gfstack.operationcenter.core.common.util; import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.core.annotation.AnnotationUtils;
import springfox.documentation.RequestHandler; import java.lang.annotation.Annotation; public class GeoRequestHandlerSelectors {
private GeoRequestHandlerSelectors() {
throw new UnsupportedOperationException();
} /**
* Any RequestHandler satisfies this condition
*
* @return predicate that is always true
*/
public static Predicate<RequestHandler> any() {
return Predicates.alwaysTrue();
} /**
* No RequestHandler satisfies this condition
*
* @return predicate that is always false
*/
public static Predicate<RequestHandler> none() {
return Predicates.alwaysFalse();
} /**
* Predicate that matches RequestHandler with handlers methods annotated with given annotation
*
* @param annotation - annotation to check
* @return this
*/
public static Predicate<RequestHandler> withMethodAnnotation(final Class<? extends Annotation> annotation) {
return new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
return null != AnnotationUtils.findAnnotation(input.getHandlerMethod().getMethod(), annotation);
}
};
} /**
* Predicate that matches RequestHandler with given annotation on the declaring class of the handler method
*
* @param annotation - annotation to check
* @return this
*/
public static Predicate<RequestHandler> withClassAnnotation(final Class<? extends Annotation> annotation) {
return new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
return declaringClass(input).isAnnotationPresent(annotation);
}
};
} /**
* Predicate that matches RequestHandler with given base package name for the class of the handler method.
* This predicate includes all request handlers matching the provided basePackage
*
* @param basePackage - base package of the classes
* @return this
*/
public static Predicate<RequestHandler> basePackage(final String... basePackage) {
return new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
String name = declaringClass(input).getPackage().getName();
for (String _package : basePackage) {
if (name.startsWith(_package)) {
return true;
}
}
return false;
}
};
} private static Class<?> declaringClass(RequestHandler input) {
return input.getHandlerMethod().getMethod().getDeclaringClass();
}
}
下载前端资源文件
https://github.com/swagger-api/swagger-ui/archive/v2.2.10.zip
备用地址:https://files.cnblogs.com/files/nihaorz/swagger-ui-2.2.10.zip
解压zip文件,拷贝dist到WebRoot下重命名为api,修改api目录下的index.html为如下内容
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<title>Swagger UI</title>
<link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32"/>
<link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16"/>
<link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
<link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
<link href='css/print.css' media='print' rel='stylesheet' type='text/css'/> <script src='lib/object-assign-pollyfill.js' type='text/javascript'></script>
<script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script>
<script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
<script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
<script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
<script src='lib/handlebars-4.0.5.js' type='text/javascript'></script>
<script src='lib/lodash.min.js' type='text/javascript'></script>
<script src='lib/backbone-min.js' type='text/javascript'></script>
<script src='swagger-ui.js' type='text/javascript'></script>
<script src='lib/highlight.9.1.0.pack.js' type='text/javascript'></script>
<script src='lib/highlight.9.1.0.pack_extended.js' type='text/javascript'></script>
<script src='lib/jsoneditor.min.js' type='text/javascript'></script>
<script src='lib/marked.js' type='text/javascript'></script>
<script src='lib/swagger-oauth.js' type='text/javascript'></script> <!-- Some basic translations -->
<!-- <script src='lang/translator.js' type='text/javascript'></script> -->
<!-- <script src='lang/ru.js' type='text/javascript'></script> -->
<!-- <script src='lang/en.js' type='text/javascript'></script> -->
<script src='lang/translator.js' type='text/javascript'></script>
<script src='lang/zh-cn.js' type='text/javascript'></script> <script type="text/javascript"> function getRootPath() {
//获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
var curWwwPath = window.document.location.href;
//获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8083
var localhostPaht = curWwwPath.substring(0, pos);
//获取带"/"的项目名,如:/uimcardprj
var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
return (localhostPaht + projectName);
} function extend(obj) {
var flag = $(obj).data("flag");
if (flag == undefined) {
flag = true;
}
if (flag) {
swaggerUi.collapseAll();
$(obj).html("恢复默认");
} else {
swaggerUi.load()
}
$(obj).data("flag", !flag)
} $(function () { $("#logo").attr("href", getRootPath() + "/api"); var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = getRootPath() + "/v2/api-docs";
} hljs.configure({
highlightSizeThreshold: 5000
}); // Pre load translate...
if (window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
window.swaggerUi = new SwaggerUi({
apisSorter: "alpha", // can also be a function
operationsSorter: "alpha", // can also be 'alpha' or a function
url: url,
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function (swaggerApi, swaggerUi) {
if (typeof initOAuth == "function") {
initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
additionalQueryStringParams: {}
});
} if (window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
$("#api_info .info_license").after("<div style='text-align:right;'><a target='_self' href='javascript:;' onclick='extend(this);'>全部折叠</a></div>");
},
onFailure: function (data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "list",
jsonEditor: false,
defaultModelRendering: 'schema',
showRequestHeaders: false,
showOperationIds: false,
validatorUrl: null
}); window.swaggerUi.load(); function log() {
if ('console' in window) {
console.log.apply(console, arguments);
}
}
});
</script>
</head> <body class="swagger-section">
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io"><img class="logo__img" alt="swagger" height="30" width="30"
src="data:images/logo_small.png"/><span class="logo__title">swagger</span></a>
<form id='api_selector'>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl"
type="text"/></div>
<div id='auth_container'></div>
<div class='input'><a id="explore" class="header__btn" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div> <div id="message-bar" class="swagger-ui-wrap" data-sw-translate> </div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>
部署项目即可开始使用swagger
参照:
https://github.com/swagger-api/swagger-ui/tree/v2.2.10
https://springfox.github.io/springfox/docs/current/
springmvc使用swagger生成rest api文档的更多相关文章
- Spring Boot 集成 Swagger 生成 RESTful API 文档
原文链接: Spring Boot 集成 Swagger 生成 RESTful API 文档 简介 Swagger 官网是这么描述它的:The Best APIs are Built with Swa ...
- 使用Swagger2Markup归档swagger生成的API文档
文章出处: http://blog.didispace.com/swagger2markup-asciidoc/ 说明 项目中使用Swagger之后,我们能够很轻松的管理API文档,并非常简单的模拟接 ...
- Swagger UI及 Swagger editor教程 API文档搭配 Node使用
swagger ui 是一个在线文档生成和测试的利器,目前发现最好用的.为啥好用呢?打开 demo,支持API自动生成同步的在线文档些文档可用于项目内部API审核方便测试人员了解 API这些文档可作为 ...
- Spring Boot学习笔记 - 整合Swagger2自动生成RESTful API文档
1.添加Swagger2依赖 在pom.xml中加入Swagger2的依赖 <!--swagger2--> <dependency> <groupId>io.spr ...
- Swagger UI教程 API 文档神器 搭配Node使用
ASP.NET Web API 使用Swagger生成在线帮助测试文档 Swagger 生成 ASP.NET Web API 前言 swagger ui是一个API在线文档生成和测试的利器,目前发现最 ...
- Golang使用swaggo自动生成Restful API文档
#关于Swaggo 相信很多程序猿和我一样不喜欢写API文档.写代码多舒服,写文档不仅要花费大量的时间,有时候还不能做到面面具全.但API文档是必不可少的,相信其重要性就不用我说了,一份含糊的文档甚至 ...
- GhostDoc:生成.NET API文档的工具 (帮忙文档)
在 Sandcastle:生成.NET API文档的工具 (帮忙文档) 后提供另一个生成API文档的工具. 1) 准备工作 安装GhostDoc Proc. 收费的哦.... 这个工具的优势是不像 ...
- 使用jsdoc-toolkit来自动生成js api文档
近来前端组小盆友开发的类库越来越多,很多情况下彼此不知道写了些什么方法,为了更好的合作提高工作效率,找了个比较好的api文档生成方法.使用jsdoc-toolkit来自动生成js api文档. 一. ...
- Grunt-jsdoc生成JS API文档
Grunt-jsdoc生成JS API文档 具体的请看官网 https://github.com/krampstudio/grunt-jsdoc 一:首先确保本机电脑上是否已经安装了nodejs和np ...
随机推荐
- 记一次Dubbo服务注册异常
公司项目重构,把dubbo版本从2.5.8升级为2.6.2.升级后在本地运行一点问题都没有:可是通过公司自研的发布系统将项目发布到测试环境的linux服务器下面后,出现了dubbo服务 ...
- hibernate 解决 org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
这是因为没有设置要更新的主键导致的,只要设置了要更新的主键就能更新成功(没有主键当然不能更新)
- 在Winform框架界面中改变并存储界面皮肤样式
在本篇介绍的Winform界面样式改变及存储操作中,是指基于DevExpress进行界面样式的变化.一般情况下,默认我们会为客户提供多种DevExpress的界面皮肤以供个人喜好选择,默认DevExp ...
- Hibernate缓存策略(一级缓存和EHcache二级缓存)
如何配置二级缓存: 第一步:导入EHcache依赖 1)Maven项目: <!--此处使用hibernate4--> <dependency> <groupId>o ...
- List对象去重碎碎念之神叨叨
前言 List集合操作去除重复数据的这种情况经常会碰到,博客园里面也有很多大神们做过,在这里主要是借鉴然后自己整理了一下,主要是为了方便自己,以后再次碰到这种去重问题,直接打开自己的链接拿起键盘就是干 ...
- (转)C#中的那些全局异常捕获
C#中的那些全局异常捕获(原文链接:http://www.cnblogs.com/taomylife/p/4528179.html) 1.WPF全局捕获异常 public partia ...
- super关键字访问父类成员
1.super只能出现在子类的方法和构造方法中: 2.super调用构造方法时只能是第一句: 3.super不能访问父类的private成员.
- SVN插件和Tomcat插件地址
SVN插件: http://subclipse.tigris.org/update_1.8.x Tomcat插件: http://tomcatplugin.sf.net/update 备注:如果svn ...
- elk之查询方式(4种)
es 在查询时, 可以指定搜索类型为下面四种: QUERY_THEN_FETCH QUERY_AND_FEATCH DFS_QUERY_THEN_FEATCH DFS_QUERY_AND_FEATCH ...
- 搭建私服-docker registry
Docke官方提供了Docker Hub网站来作为一个公开的集中仓库.然而,本地访问Docker Hub速度往往很慢,并且很多时候我们需要一个本地的私有仓库只供网内使用.Docker仓库实际上提供两方 ...