Spring Boot中使用Swagger2構建RESTful API文檔

轉載聲明:商業轉載請聯繫作者獲得授權,非商業轉載請註明出處 © wekri

隨着時間推移,不斷修改接口實現的時候都必須同步修改接口文檔,而文檔與代碼又處於兩個不同的媒介,除非有嚴格的管理機制,不然很容易導致不一致現象

添加Swagger2依賴

pom.xml中添加swagger2依賴

        <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.2.2</version>
        </dependency>

創建swagger2配置

package com.mycompany.financial.nirvana.core.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;

/**
 * Created by liuweiguo on 2017/2/13.
 */
@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("api")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mycompany.financial.nirvana.admin.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("有魚小貸聯盟商戶端接口")//大標題
                .description("有魚小貸聯盟商戶端接口")//詳細描述
                .termsOfServiceUrl("http://blog.csdn.net/eacter")
                .contact("有魚團隊")//作者
                .version("1.0")//版本
                .build();
    }


    @Bean
    public Docket demoApi() {
        return new Docket(DocumentationType.SWAGGER_2).groupName("demo")//創建多個分組
                .apiInfo(demoApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mycompany.financial.nirvana.demo"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo demoApiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構建RESTful APIs")//大標題
                .description("Swagger2 demo")//詳細描述
                .termsOfServiceUrl("http://blog.csdn.net/eacter")
                .contact("有魚團隊")//作者
                .version("1.0")//版本
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }

}

通過@Configuration註解讓spring加載配置,@EnableSwagger2啓用Swagger2

再通過createRestApi函數創建Docket的Bean之後,apiInfo()用來創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。select()函數返回一個ApiSelectorBuilder實例用來控制哪些接口暴露給Swagger來展現,本例採用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,併產生文檔內容(除了被@ApiIgnore指定的請求)。

添加文檔內容

package com.mycompany.financial.nirvana.demo.controller;

import com.mycompany.financial.nirvana.demo.bean.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;

/**
 * Swagger動態文檔demo
 * Created by liuweiguo on 2017/2/13.
 */
@Api(value = "Swagger動態文檔demo", description = "this is desc", position = 100, protocols = "http")
@RestController
@RequestMapping(value = "/demo/users")
public class SwaggerController {
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<>());

    @ApiOperation(value = "獲取用戶列表", notes = "查詢用戶列表")
    @RequestMapping(value = {""}, method = RequestMethod.GET)
    @ApiResponses({
            @ApiResponse(code = 100, message = "喲吼")
    })
    public List<User> getUserList() {
        return new ArrayList<>(users.values());
    }

    @ApiOperation(value = "創建用戶", notes = "根據User對象創建用戶")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "用戶名", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "age", value = "年齡", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "ipAddr", value = "ip喲", required = false, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "", method = RequestMethod.POST)
    public String postUser(@ApiIgnore User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @ApiOperation(value = "獲取用戶詳細信息", notes = "根據url的id來獲取用戶詳細信息")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @ApiOperation(value = "更新用戶詳細信息", notes = "根據url的id來指定更新對象,並根據傳過來的user信息來更新用戶詳細信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", paramType = "path"),
            @ApiImplicitParam(name = "name", value = "用戶名", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "age", value = "年齡", required = true, dataType = "String", paramType = "form")
    })
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String putUser(@PathVariable Long id, @ApiIgnore User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);
        return "success";
    }

    @ApiOperation(value = "刪除用戶", notes = "根據url的id來指定刪除對象")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }


    @ApiIgnore //使用這個註解忽略這個接口
    @ApiOperation(value = "不想顯示到文檔的接口", notes = "不想顯示到文檔的接口")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "Long", paramType = "form")
    @RequestMapping(value = "/ignoreMe/{id}", method = RequestMethod.DELETE)
    public String ignoreMe(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }
}

常用註解

  • @Api:將Controller標記爲Swagger文檔資源。

  • @ApiOperation:描述一個類的一個方法,或者說一個接口

  • @ApiImplicitParams :多個參數描述
  • @ApiImplicitParam:單個參數描述

  • @ApiModel:用對象來接收參數

  • @ApiModelProperty:用對象接收參數時,描述對象的一個字段

其它

  • @ApiResponse:HTTP響應其中1個描述
  • @ApiResponses:HTTP響應整體描述

API文檔訪問與調試

完成上述操作,啓動Spring Boot程序,Swagger會默認把所有Controller中的RequestMapping方法都生成API出來。訪問:http://localhost:8080/swagger-ui.html就能看到生成的RESTful API的頁面。
這裏寫圖片描述

點開具體的API請求,Try it out!

官網Live Demo http://petstore.swagger.io/

文檔數據地址

http://127.0.0.1:8080/v2/api-docs

常見問題

訪問不到swagger-ui

到GitHub上找到Swagger-ui項目:https://github.com/swagger-api/swagger-ui,將dist下所有內容拷貝到本地項目web項目中, 並修改 index.html,把默認的數據地址換成自己的數據地址

//url = "http://petstore.swagger.io/v2/swagger.json";
url = "http://localhost:8090/v2/api-docs";

demo地址

https://code.csdn.net/Eacter/springboot-samples/tree/master/swagger

參考信息

Swagger-UI官方網站
Spring boot 2.0 – swagger2 整合 swagger-ui.html 打不開問題
github:swagger-ui

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章