springboot配置 Swagger2 接口文檔引擎

0. 關於Swagger

Swagger是一個功能強大且易於使用的API開發人員工具套件,適用於團隊和個人,支持從整個API生命週期(從設計和文檔到測試和部署)的開發。

1. 增加 Swagger2 所需依賴

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

2. 配置 Swagger2

創建一個名爲 Swagger2Config 的 Java 配置類:

@Configuration
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.funtl.itoken.service.admin.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("iToken API 文檔")
                .description("iToken API 網關接口,http://www.funtl.com")
                .termsOfServiceUrl("http://www.funtl.com")
                .version("1.0.0")
                .build();
    }
}

3. 啓用 Swagger2

在Application類上加上註解 @EnableSwagger2 表示開啓 Swagger

4. 使用 Swagger2

eg:

     /**
     * 類別列表分頁查詢
     *
     * @param pageNum
     * @param pageSize
     * @param tbCatagory
     * @return
     */
    @ApiOperation(value = "類別列表分頁查詢接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "頁碼", required = true, dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每頁記錄數", required = true, dataType = "int"),
            @ApiImplicitParam(name = "tbCatagory", value = "查詢條件對象", required = false, dataTypeClass = TbCatagory.class)
    })
    @GetMapping("page/{pageNum}/{pageSize}")
    public BaseResult page(
            @PathVariable(required = true) int pageNum,
            @PathVariable(required = true) int pageSize,
            @RequestParam(required = false) TbCatagory tbCatagory
    ) throws Exception {

        PageInfo pageInfo = catagoryService.page(pageNum, pageSize, tbCatagory);
        // 分頁後的結果集
        List<TbCatagory> list = pageInfo.getList();
        // 封裝 Cursor 對象
        BaseResult.Cursor cursor = new BaseResult.Cursor();
        cursor.setTotal(new Long(pageInfo.getTotal()).intValue());
        cursor.setOffset(pageInfo.getPageNum());
        cursor.setLimit(pageInfo.getPageSize());
        return BaseResult.ok(list, cursor);
    }

5. 查看文檔

地址:http://ip:port/swagger-ui.html
可以在這裏進行接口的測試
在這裏插入圖片描述

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