SpringBoot Springfox RESTful API(下篇)- 構建 Swagger API文件

                                    

 

上篇我們講了如何和利用MockMvc來測試我們的RESTfulAPI,沒看過的請移步:(https://my.oschina.net/codingcloud/blog/1588662),但MockMvc需要編寫大量的測試程式碼,在很多的快速迭代的專案中並不是那麼適用。所以這篇我們會學習一個更便捷的API工具:Swagger

什麼是Swagger?

Swagger是全球最大的OpenAPI規範(OAS)API開發工具框架,支援從設計和文件到測試和部署的整個API生命週期的開發

Swagger官網快速入口:https://swagger.io

 

如何將Swagger和SpringBoot整合?

一、引入swagger依賴jar包的maven配置

<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>

二、編寫java程式碼

1、編寫SwaggerConfigruation.java 這類來負責管理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;

/**
 *
 * Swagger2 配置類
 *
 * <p>
 *     @Configuration 讓spring載入該類配置
 *     @EnableSwagger2 啟用swagger2
 * </p>
 */
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

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

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("文件中心")
                .termsOfServiceUrl("https://my.oschina.net/codingcloud/blog")
                .contact("codingcloud")
                .license("北京xxx有限公司")
                .version("1.0")
                .description("備註資訊")
                .build();
    }
}

2、建立一個UserController.java 我們編寫的api介面

只需要關注幾個註解即可, @ApiOperation 和 @ApiImplicitParam


import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 構建restful API文件
 * Created by nasheng.yun on 2017/12/12.
 */
@SuppressWarnings("Duplicates")
@RestController
@RequestMapping(value = "user")
public class UserController {

    // 建立執行緒安全的map
    static Map<String,User> users = new ConcurrentHashMap<>();

    @ApiOperation(value = "獲取使用者列表",notes = "xxx")
    @GetMapping(value = "getUserList")
    public List<User> list(){
        List<User> userList = new ArrayList<>(users.values());

        System.out.println("UserController.list");
        return userList;
    }

    @ApiOperation(value = " 建立使用者",notes = "根據User物件來建立使用者")
    @ApiImplicitParam(name = "user",value = "使用者實體User",required = true,dataType = "User")
    @PostMapping("createUser")
    public String post(@RequestBody User user){

        System.out.println("UserControllerRestfulAPI.post"   user);
        users.put(user.getId(),user);

        System.out.println("UserController.post");
        return "success";
    }

    @ApiOperation(value = "更新使用者",notes = "根據使用者id更新使用者")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "使用者id",required = true,dataType = "String"),
            @ApiImplicitParam(name = "user",value = "使用者實體User",required = true,dataType = "User")
    })
    @PutMapping("updateUser/{id}")
    public String put(@PathVariable String id,@RequestBody User user){
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id,u);
        System.out.println("UserController.put");
        return "success";
    }

    @ApiOperation(value = "查詢使用者詳情")
    @ApiImplicitParam(name = "id",value = "使用者id",required = true,dataType = "String")
    @GetMapping(value = "userDetail/{id}")
    public User detail(@PathVariable String id){
        System.out.println("UserController.detail");
        return users.get(id);
    }

    @ApiOperation(value = "刪除使用者")
    @ApiImplicitParam(name = "id",value = "使用者id",required = true,dataType = "String")
    @DeleteMapping(value = "deleteUser/{id}")
    public String delete(@PathVariable String id){
        users.remove(id);
        System.out.println("UserController.delete");
        return "success";
    }

}

程式碼寫完了,下面我們來啟動專案測試一下。

專案啟動後,在瀏覽器輸入:http://localhost:8080/swagger-ui.html  來訪問swagger頁面,如圖:

 

先測試建立使用者,填寫測試資料,點選左下角的 Try it out 按鈕

返回結果:

 

好了到此為止,我們的swagger整合springboot就完成了,有什麼問題請隨時指教。

 

參考文件:https://swagger.io/

http://blog.didispace.com/springbootswagger2/


(adsbygoogle = window.adsbygoogle || []).push({});

function googleAdJSAtOnload() {
var element = document.createElement(“script”);
element.src = “//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”;
element.async = true;
document.body.appendChild(element);
}
if (window.addEventListener) {
window.addEventListener(“load”, googleAdJSAtOnload, false);
} else if (window.attachEvent) {
window.attachEvent(“onload”, googleAdJSAtOnload);
} else {
window.onload = googleAdJSAtOnload;
}