API管理-基於SpringBoot專案整合swagger實現介面文件自動生成
阿新 • • 發佈:2019-06-24
1. 為什麼要使用swagger?
上一次部落格(API管理-使用開源xxl-api專案管理介面)中我也提到過介面文件在整個生命週期中的重要性以及使用開源xxl-api的優缺點,缺點就是沒法自動完成介面文件的生成,而是手動的錄入,這樣的話跟我們傳統的通過編寫word來管理介面文件也沒什麼區別;而swagger卻是通過開發者在編寫介面的時候就已經通過指定的註解標註好介面的資訊,在啟動的時候swagger會自動生成對應的介面文件。
2. SpringBoot配置使用方式
- 配置pom.xml依賴
<!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> <!-- <version>2.8.0</version> --> </dependency> <!-- springfox-swagger原生ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
- 配置SwaggerConfig類
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.api.rest.controller")) .paths(PathSelectors.any()) .build(); // .build().enable(false); // 線上關閉介面 } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("智慧衛檢-監督員系統") .description("監管系統") .termsOfServiceUrl("http://www.zhihuiweijian.com/") //.contact(contact) .version("1.0") .build(); } }
- 配置MvcConfig類
@Configuration public class MvcConfig extends WebMvcConfigurationSupport { /** * * 功能描述: * 配置靜態資源,避免靜態資源請求被攔截 * @auther: Tt(yehuawei) * @date: * @param: * @return: */ public void addResourceHandlers(ResourceHandlerRegistry registry) { //如果靜態檔案放到了classpath 下,就如下配置。 registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); /*放行swagger*/ registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } }
- 以規定的註解編寫介面資訊
@ApiOperation(value="賬號密碼登入", notes="賬號密碼登入")
@ApiImplicitParams({
@ApiImplicitParam(name = "mobile", value = "賬號", required = true, dataType = "String"),
@ApiImplicitParam(name = "password", value = "密碼", required = true, dataType = "String")
})
@RequestMapping(value="accountLogin")
public ApiCommonResultVo login(String mobile, String password) {}
- 啟動專案、訪問地址、檢視介面資訊:http://localhost:8080/swagger-ui.html
- 效果圖
3. 總結
Swagger API 介面文件生成工具的利與弊,對於使用swagger利弊這邊文章已經解釋的很清楚了,雖然通過這種方式整合swagger後有一個統一的介面可以檢視介面資訊了,但這個springfox-swagger-ui版本的並不支援介面文件的下載以便於離線檢視,還有就是原生的ui使用起來總感覺不順手,所以又有人基於swagger的介面方式自定義開發了基於bootstrap的ui並擴充套件了部分功能,詳細請參考部落格:API管理-捨棄springfox-swagger-ui,採用功能更加豐富的swagger-bootstrap-ui。