随着互联网技术的发展,现在的网站架构基本都由原来的后端渲染,变成了:前端渲染、前后端分离的形态,而且前端技术和后端技术在各自的道路上越走越远。
前端和后端的唯一联系,变成了API接口;API文档变成了前后端开发人员联系的纽带,变得越来越重要,swagger
就是一款让我们更好地书写API文档的框架。swagger可以用来显示API文档。
我们在基于spring框架进行java开发时,当需要使用swagger生成API文档时,需要先添加swagger的jar包依赖。我们以在maven项目管理工具中开发项目为例,在pom.xml中添加如下依赖:
<dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>0.9.5</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.7</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.7</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>com.fasterxml</groupId> <artifactId>classmate</artifactId> <version>1.3.1</version> </dependency>
接着,要写一个swagger的核心配置类,如下所示:
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; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration//声明此类是一个swagger的核心配置类 @EnableSwagger//启用Swagger @EnableWebMvc//启用SpringMVC public class SwaggerConfig { //给SpringSwaggerConfig进行赋值 private SpringSwaggerConfig springSwaggerConfig; @Autowired public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) { this.springSwaggerConfig = springSwaggerConfig; } /** * 自定义实现 customImplementation * @return */ @Bean //再配置一个SwaggerSpringMvcPlugin 的bean,将来SpringMVC生成文档时要用 public SwaggerSpringMvcPlugin customImplementation(){ return new SwaggerSpringMvcPlugin(this.springSwaggerConfig) .apiInfo(apiInfo()) .includePatterns(".*?"); } /** * title; description; terms of serviceUrl; contact email; license type; license url; * @return */ private ApiInfo apiInfo(){ ApiInfo apiInfo = new ApiInfo( "XXX项目接口文档", "企业版,为企业用车提供一站式解决方案:海量优质车型,实时调度,会议、商务用车尽享便捷;多种灵活用车方式,快车、专车、接送机一键完成", "http://192.168.1.236", "联系邮箱", "许可证的类型", "许可证的链接" ); return apiInfo; } }
然后,在springmvc-config.xml配置文件里的扫描注解里加上@Configuration,如下所示:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--springmvc 只管扫描 controller包--> <context:component-scan base-package="com.itszt.XXX.controller,com.itszt.XXX.controller.swagger"> <context:include-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/> </context:component-scan> <!--支持注解-> <mvc:annotation-driven> <!--让我们的Adapter有json 转换能力--> <mvc:message-converters> <ref bean="jsonconverter"></ref> </mvc:message-converters> </mvc:annotation-driven> <!--jackson给我们提供的一个json转换器--> <bean id="jsonconverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--静态资源的处理--> <mvc:resources mapping="/pages/*" location="/htmls/"></mvc:resources> <mvc:resources mapping="/swagger/**/*" location="/swagger/"></mvc:resources> <bean class="com.itszt.XXX.controller.swagger.SwaggerConfig"></bean> <bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig"></bean> </beans>
接下来,下载swagger- UI,添加到 SpringMVC 的静态文件的目录里。
然后,在使用中,实体类上用注解@ApiModel(description = "返回的结果"),其下属性用注解@ApiModelProperty(notes = "注册失败的错误信息");
控制器上用注解@Api(description="用户中心模块",value = "用户相关操作"),其下方法用注解@ApiOperation(notes = "验证用户接口",value = "用户登录使用的方
法",httpMethod = "GET"),方法的参数前用注解@ApiParam(name="username",required = true,value = "用户名")。
最后,我们在浏览器地址栏里访问 http://localhost/api-docs,即可看到页面swagger包下的index.html动态显示的相应内容:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <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 type="text/javascript"> $(function () { var url = window.location.search.match(/url=([^&]+)/); if (url && url.length > 1) { url = decodeURIComponent(url[1]); } else { // url = "http://petstore.swagger.io/v2/swagger.json"; url = "http://localhost/api-docs"; } hljs.configure({ highlightSizeThreshold: 5000 }); // Pre load translate... if(window.SwaggerTranslator) { window.SwaggerTranslator.translate(); } window.swaggerUi = new SwaggerUi({ 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(); } }, onFailure: function(data) { log("Unable to Load SwaggerUI"); }, docExpansion: "none", jsonEditor: false, defaultModelRendering: 'schema', showRequestHeaders: false }); 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>