swagger的說明、配置及使用


 

一、What is swagger?

官方介紹Swagger是一個規范且完整的框架,提供描述、生產、消費和可視化RESTful Web Service。
專業角度:Swagger是由龐大工具集合支撐的形式化規范。這個集合涵蓋了從終端用戶接口、底層代碼庫到商業API管理的方方面面。

二、Why use the swagger?

  1. 講個故事:在2014年時候,我和另一個小伙伴加入到一個實驗室,開始了我們漫長的應用開發之路(這也是第一次做項目)。因為只有兩個人,我做后台,他做Android,分工很明確的。在一開始,我們並沒有關注API相關的內容,隨手拈來,我說什么,他就調用什么。當然,也沒有什么API文檔提供。以至於到現在,我想更新升級系統,才發現,我們寫的代碼是有多爛,連自己都不忍心去看的。所以說在項目開始就定一個契約,雙方(前端后台)就API相關的內容,包括路徑、參數、類型等達成一致,當然,這份契約並不是一旦創建就不能修改的,而且,如果一開始沒有設計好,很有可能會頻繁的修改。
  2. 作為一個很懶的碼代碼的猿呢,對於一些API的理解總是很模糊不清,但是,總想着能直接驗證一下自己的理解就好了,而不是需要去項目寫測試代碼來驗證自己的想法。所以說,API文檔應該有直接運行的能力。而Swagger就是這樣的一個東西,它可以為已有項目的生成具備執行能力的樣式化API文檔,這樣可以極大的方便程序員對前端后台進行對接整合。

三、use the swagger

1. 開發環境介紹
  • maven 3.3
  • jdk 8+
  • spring 4.2.5
  • mybatis 3.4.1
  • swagger 1.0.2
2. 在pom.xml文件中添加swagger相關依賴
<!-- swagger-mvc --> <dependency> <groupId>com.mangofactory</groupId> <artifactId>swagger-springmvc</artifactId> <version>1.0.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.6</version> </dependency> <!-- swagger-mvc -->
3. 自定義對swagger的配置

對於swagger的配置,其實對自定義一個與swagger相關的Config類,可以通過Java編碼的實現配置。代碼如下:

package com.hp.common.swagger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.models.dto.ApiInfo; import com.mangofactory.swagger.paths.SwaggerPathProvider; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; /** * * @ClassName: SwaggerConfig.java * @Description: Swagger配置類 * * @version: v1.1.0 * @author: xiangdong * @date: Mar 16, 2017 */ public class SwaggerConfig extends WebMvcConfigurerAdapter { private SpringSwaggerConfig springSwaggerConfig; @Autowired public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) { this.springSwaggerConfig = springSwaggerConfig; } /** * 鏈式編程 來定制API樣式 后續會加上分組信息 * * @return */ @Bean public SwaggerSpringMvcPlugin customImplementation(){ return new SwaggerSpringMvcPlugin(this.springSwaggerConfig) .apiInfo(apiInfo()) .includePatterns(".*?"); } private ApiInfo apiInfo() { ApiInfo apiInfo = new ApiInfo("API接口測試平台", "提供后台所有Restful接口", "www.flyeast.top", "shexd1001@gmail.com", "β客棧", "www.flyeast.top"); return apiInfo; } @Override public void configureDefaultServletHandling( DefaultServletHandlerConfigurer configurer) { configurer.enable(); } }

//第二種配置類

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger {

@Bean
public Docket appApi() {
return new Docket(DocumentationType.SWAGGER_2).enable(true)
.groupName("appApi")
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(true)
.pathMapping("/")// base,最終調用接口后會和paths拼接在一起
.select()
// .paths(or(regex("/.*")))//過濾的接口
.build()
.apiInfo(appApiInfo());
}
private ApiInfo appApiInfo() {
return new ApiInfoBuilder()
.title("嘻嘻哈哈")
.description("小系統")
.version("1.0")
.build();
}
}





3. 注入SwaggerConfig類

上面這段對swagger進行了基本的配置,現在需要將其注入到spring容器中,完成在程序加載之后對所有接口掃描解析的功能呢,在spring相關的配置文件中加入以下代碼:

    <!-- swagger配置信息 --> <bean class="com.mangofactory.swagger.configuration.SpringSwaggerConfig" />
4. 配置需要解析的接口方法

以下代碼是Controller中的一個方法,@ApiOperation注解對這個方法進行了說明,@ApiParam注解對方法參數進行了說明。關於其他注解,可以查看源碼或其他幫助文檔;

/** * DELETE 刪除用戶 * @return */ @ApiOperation(value = "刪除用戶信息", notes = "刪除用戶", httpMethod = "DELETE", produces = MediaType.APPLICATION_JSON_VALUE) @RequiresPermissions("sysuser:list:delete") @RequestMapping(value = "/list/{accountId}/delete", method = RequestMethod.DELETE) @ResponseBody public AjaxResult delete(@PathVariable Long accountId) { systemUserService.deleteSysUser(accountId); return success(true); }
5. 對Swagger-UI進行配置

Swagger掃描解析得到的是一個json文檔,所以對於用戶使用不是很方便,但是通過swagger-ui,可以友好的展示解析得到的接口說明內容。
這里 獲取其所有的 dist 目錄下東西放到需要集成的項目里,本文放入 src/main/webapp/目錄下。
修改index.html文件,默認是從連接http://petstore.swagger.io/v2/swagger.json獲取 API 的 JSON,我們需要將url值修改為http://{ip}:{port}/{projectName}/api-docs的形式,如http://localhost:8080/CloudTi/api-docs

6. 運行項目,訪問URL

URL是自己在index.html中定義的URL


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM