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="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
参照: