1. 程式人生 > >SpringBoot整合Swagger2搭建API在線文檔

SpringBoot整合Swagger2搭建API在線文檔

type 版本 pri ati 技術 實體類 -c map ans

Swagger,中文“拽”的意思,它是一個功能強大的在線API在線文檔,目前它的版本為2.x,所以稱為Swagger2。Swagger2提供了在線文檔的查閱和測試功能。利用Swagger2很容易構建RESTful風格的API,在SpringBoot中集成Swagger2,步驟如下。

1.引入依賴

        <!--Swagger2-->
        <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.配置Swagger2

@Configuration
@EnableSwagger2
public class Swagger2Config {


    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.yuehsutong.swagger2.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("SpringBoot利用Swagger構建API文檔")
                .description("描述內容")
                .termsOfServiceUrl("服務url")
                .version("版本")
                .build();
    }

}

3.寫Swagger註解

@RestController
public class DemoController {

    @RequestMapping(value = "/users",method = RequestMethod.GET)
    @ApiOperation(value = "接口名稱", notes = "接口的詳細說明")
    public Object users(){
        Map<String,String> map = new HashMap<>();
        map.put("one","zhansan");
        return map;
    }
}

4.瀏覽Swagger-UI在線文檔

默認訪問路徑:http://localhost:8080/swagger-ui.html

技術分享圖片

5.常用Swagger註解

  • @Api()用於類,表示標識這個類是swagger的資源
  • @ApiOperation()用於方法,表示一個http請求的操作
  • @ApiParam()用於方法,參數,字段說明;表示對參數的添加元數據(說明或是否必填等)
  • @ApiModel()用於類,表示對類進行說明,用於參數用實體類接收
  • @ApiModelProperty()用於方法,字段,表示對model屬性的說明或者數據操作更改
  • @ApiIgnore()用於類,方法,方法參數,表示這個方法或者類被忽略
  • @ApiImplicitParam() 用於方法,表示單獨的請求參數
  • @ApiImplicitParams() 用於方法,包含多個 @ApiImplicitParam

學習資源

Swagger-Core Annotations

SpringBoot整合Swagger2搭建API在線文檔