1. 程式人生 > >springfox-swagger2 || rap

springfox-swagger2 || rap

一個介紹rap和swagger的網站
rap是阿里自研的一個api工具,以前用過需要手寫儲存,給前端的是一個壓縮後的md檔案列表,沒接觸swagger之前還以為是高階的。
近期接觸swagger,發現整合到springboot還是很簡單的,不需要配置,可直接使用提供的ui元件,不過很多註解會跟系統程式碼耦合在一起。以下是整合方法:
1、新增依賴

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

2、配置類
使用@EnableSwagger2開啟swagger2

@Profile({"dev", "local", "test"})
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.changhf.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("DEMO Restful APIs")
                .description("這個一個springboot整合swagger提供api文件的demo")
                // .termsOfServiceUrl("http://blog.csdn.net/chang_li")
                .contact(new Contact("changhf", "www.demo.com", "
[email protected]
")) .version("1.0") .build(); } }

3、註解記錄

  1. @ApiOperation在指定的路徑上,對一個操作或HTTP方法進行描述。
    value對操作的簡單說明,長度為120個字母,60個漢字。
    notes對操作的詳細說明。

  2. @ApiImplicitParams
    註解ApiImplicitParam的容器類,以陣列方式儲存。

  3. @ApiImplicitParam
    對API的單一引數進行註解。
    name引數名稱
    value引數的簡短描述
    required

    是否為必傳引數
    dataType引數型別,可以為類名,也可以為基本型別(String,int、boolean等)
    paramType引數的傳入(請求)型別,可選的值有path, query, body, header or form。
    defaultValue引數預設值

    @ApiOperation(value = "分配任務", notes = "分配任務,即指定當前節點執行人")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "workItemId", value = "工作項id", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "使用者id", required = true, dataType = "Long", paramType = "query", defaultValue = "110")
    })
    @GetMapping("/distributeTask")
    public WorkItemTaskDTO distributeTask(@RequestParam Long workItemId, @RequestParam Long userId) {
        try {
            return workflowService.distributeTask(workItemId, new UserDTO(userId, "lisi", 902L), null);
        } catch (Exception e) {
            log.error("分配任務失敗", e);
        }
        return null;
    }

4、啟動應用程式,訪問localhost:8080/swagger-ui.html,點選Show/Hide即可