SpringBoot集成Swagger構建RESTful API文檔

[Swagger2 提供一下能力]:

   1.隨項目自動生成強大RESTful API文檔

   2.API文檔與代碼整合在一起,便於同步更新API說明

   3.頁面測試功能來調試每個RESTful API

[集成Swagger2步驟]:
1.修改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>
2.創建Swagger2配置類

在spring boot啓動類所在包或子包中創建Swagger配置類SwaggerConfig.java,如下:


SwaggerConfig.java內容如下:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select().apis(RequestHandlerSelectors.basePackage("com.zhaopin.pinebase"))
                // 指定掃描包下面的註解
                .paths(PathSelectors.any()).build();
    }

    // 創建api的基本信息
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("集成Swagger2構建RESTful APIs").description("高性能在線測試接口文檔自動生成開發平臺").termsOfServiceUrl("https://www.xxxx.com").contact(" Pine Sir")
                .version("1.0.0")
                .build();
    }
}
3.創建Controller: SwaggerController.java
@RestController
@RequestMapping("/swagger")
public class SwaggerController {


    @ApiOperation(value = "獲取用戶信息", notes = "根據id來獲取用戶詳細信息")
    @ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "String")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Map<String, String> getInfo(@PathVariable String id) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "張三");
        map.put("age", "34");
        return map;
    }

}

4.啓動Spring boot,訪問Swagger UI界面:http://localhost:8080/swagger-ui.html

5.測試API



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