1. 程式人生 > >spring-boot整合swagger( 提供封裝的starter原始碼)

spring-boot整合swagger( 提供封裝的starter原始碼)

swagger簡介

Swagger™的目標是為REST APIs 定義一個標準的,與語言無關的介面,使人和計算機在看不到原始碼或者看不到文件或者不能通過網路流量檢測的情況下能發現和理解各種服務的功能。當服務通過Swagger定義,消費者就能與遠端的服務互動通過少量的實現邏輯。類似於低階程式設計介面,Swagger去掉了呼叫服務時的很多猜測。
瀏覽 Swagger-Spec 去了解更多關於Swagger 專案的資訊,包括附加的支援其他語言的庫。

pom.xml(新增依賴)
<dependency>
    <groupId>io.springfox</groupId
>
<artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency
>
swagger配置檔案
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors
; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableSwagger2 @Configuration @EnableWebMvc //需要掃描的介面包 public class Swagger2Config { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } // 一些介面文件資訊的簡介 private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使用Swagger2構建RESTful APIs") .description("spring Boot 中構建RESTful API") .termsOfServiceUrl("") .contact("caizi") .version("1.0") .build(); } }
swagger 註解用法
 1.對整個controller的描述註解
   @Api(value = "資訊", description = "管理資訊的API")
   2.對每一個介面的描述
    @ApiOperation(value = "修改資訊", notes = "資訊物件,資訊標籤,資訊id")
   3.對每個引數進行描述
   @ApiParam(required = true, name = "postData",value = "使用者資訊json資料") @RequestParam("tagData") String tagData
示例(線上測試時,需要注意引數的paramType引數的型別)
@Api(value = "CorpusController", description = "管理語料的方法")
public class CorpusController {
    @Autowired
    ICorpusService iCorpusService;

    @GETMapping(value = "/getCorpusByUserName")
    @ApiOperation(value = "getCorpusByUserName", notes = "獲取語料")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "使用者賬號", required = true, dataType = "STRING",, paramType = "query"),
            @ApiImplicitParam(name = "corpusType", value = "語料分組型別", required = true, dataType = "STRING",, paramType = "query")
    })
    public String getCorpusByUserName(@RequestParam("userName") String userName,
                                      @RequestParam("corpusType") String corpusType) {
        String result = iCorpusService.getCorpusByUserName(userName, corpusType).toString();
        return result;
    }

}
使用
// 如果釋出伺服器可能路徑還需要加上專案名
http://ip:port/swagger-ui.html

image

結語

當然這些公共的配置,都可以配置成spring-boot-starter這樣方便後面的呼叫,同時也能更好的維護。

// swagger-spring-boot-starter 原始碼下載地址
github: https://github.com/zg091418/swagger2springbootstarter