Spring Boot系列十九 Spring boot集成 swagger

Swagger簡述

Swagger 是一款RESTFUL接口的文檔在線自動生成+功能測試功能軟件 Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。整體目標是使客戶端和文件系統做爲服務器以一樣的速度來更新。文件的方法,參數和模型緊密集成到服務器端的代碼,容許API來始終保持同步html

Spring Boot集成Swagger

本文涉及的工程: swaggerjava

pom.xml swagger須要引入以下的jargit

<!--  引入swagger包 -->
<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>
複製代碼

@EnableSwagger2 使用@EnableSwagger2註解在Control類上就能夠swagger的功能github

@RestController
@EnableSwagger2 // 啓動swagger註解
// api-value:定義名稱,若是沒有定義,則默認顯示類名
@Api(value = "Swagger Test Control", description = "演示Swagger用法的Control類", tags = "Swagger Test Control Tag")
public class SwaggerTestCtl {
..
}
複製代碼

執行啓動類 執行啓動類,訪問以下鏈接 http://127.0.0.1:8080/swagger-ui.html#/ 就能夠進入swagger頁面,進行接口測試,界面以下: spring

這裏寫圖片描述

ApiInfo類

咱們建立ApiInfo實例,咱們爲swagger配置更多的接口說明apache

@Bean
public Docket api() {
	return new Docket(DocumentationType.SWAGGER_2)
		.apiInfo(getApiInfo())
		// .pathMapping("/")// base,最終調用接口後會和paths拼接在一塊兒
		.select()
		// .paths(Predicates.or(PathSelectors.regex("/api/.*")))//過濾的接口
		.apis(RequestHandlerSelectors.basePackage("com.hry.swagger.ctl")) //過濾的接口
		.paths(PathSelectors.any())
		.build();
}

private ApiInfo getApiInfo() {
	// 定義聯繫人信息
	Contact contact = new Contact("hryou0922","https://github.com/hryou0922", "hryou0922@126.com");
	return new ApiInfoBuilder()
		.title("演示 Swagger 的用法") // 標題
		.description("演示Swagger中各類註解的用法") // 描述信息
		.version("1.1.2") // //版本
		.license("Apache 2.0")
		.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
		.contact(contact)
		.build();
}
複製代碼

重啓服務,界面以下: json

這裏寫圖片描述

swagger的註解

swagger的註解概述

咱們可使用swagger定義更詳細接口說明api

@Api:用在類上,標誌此類是Swagger資源
	value:接口說明
	tags:接口說明,能夠在頁面中顯示。能夠配置多個,當配置多個的時候,在頁面中會顯示多個接口的信息

@ApiOperation:用在方法上,描述方法的做用

@ApiImplicitParams:包裝器:包含多個ApiImplicitParam對象列表

@ApiImplicitParam:定義在@ApiImplicitParams註解中,定義單個參數詳細信息
		○ paramType:參數放在哪一個地方
			§ header-->請求參數的獲取:@RequestHeader
			§ query-->請求參數的獲取:@RequestParam
			§ path(用於restful接口)-->請求參數的獲取:@PathVariable
			§ body(以流的形式提交 僅支持POST)
			§ form(以form表單的形式提交 僅支持POST)
		○ name:參數名
		○ dataType:參數的數據類型 只做爲標誌說明,並無實際驗證
			§ Long
			§ String
		○ required:參數是否必須傳
			§ true
			§ false
		○ value:參數的意義
		○ defaultValue:參數的默認值

@ApiModel:描述一個Swagger Model的額外信息
	@ApiModel用在類上,表示對類進行說明,用於實體類中的參數接收說明
	
@ApiModelProperty:在model類的屬性添加屬性說明

@ApiParam:用於Controller中方法的參數說明

@ApiResponses:包裝器:包含多個ApiResponse對象列表
	
@ApiResponse:定義在@ApiResponses註解中,通常用於描述一個錯誤的響應信息
		○ code:錯誤碼,例如400
		○ message:信息,例如"請求參數沒填好"
		○ response:拋出異常的類
		
@Authorization	Declares an authorization scheme to be used on a resource or an operation.

@AuthorizationScope	Describes an OAuth2 authorization scope.
複製代碼

##演示使用註解demo 本節咱們演示上節的註解如何使用 ###@Api 用在類上,標誌此類是Swagger資源,對接口更加詳細說明bash

@RestController
@EnableSwagger2 // 啓動swagger註解
@Api(value = "Swagger Test Control", description = "演示Swagger用法的Control類", tags = "Swagger Test Control Tag")
public class SwaggerTestCtl {

}
複製代碼

結果以下: 服務器

這裏寫圖片描述

###@ApiOperation 用在方法上,描述方法的做用

// 方法的說明
@ApiOperation(value = "根據id獲取記錄", response = Student.class)
// 定義請求參數
@ApiImplicitParams({ @ApiImplicitParam(paramType = "query", dataType = "String", name = "id", value = "主鍵", required = true) })
public Student queryById(String id){
    System.out.println("queryById id = " + id);
    return new Student();
}
複製代碼

結果以下:

這裏寫圖片描述

@ApiImplicitParams 和 @ApiImplicitParam

// 定義請求參數
@ApiImplicitParams({ @ApiImplicitParam(paramType = "query", dataType = "String", name = "id", value = "主鍵", required = true) })
public Student queryById(String id){
   System.out.println("queryById id = " + id);
   return new Student();
}

複製代碼

結果以下:

這裏寫圖片描述

###@ApiModel 和@ApiModelProperty

定義model類

@ApiModel( description = "學生")
public class Student {
    @ApiModelProperty(value = "主鍵id")
    private String id;
    @ApiModelProperty(value = "名稱", required = true)
    private String name;
    @ApiModelProperty(value = "年齡", required = true)
    private int age;
…
}
複製代碼

在方法使用

@RequestMapping(value = "/update", method = {RequestMethod.POST})
// 方法說明
@ApiOperation(value = "添加學生記錄", notes="傳遞複雜對象DTO",produces = "application/json")
public int update(@RequestBody Student student){
    System.out.println("update student = " + student);
    return 1;
}
複製代碼

結果以下:

這裏寫圖片描述

@ApiResponses和@ApiResponse

@RequestMapping(value = "/del", method = {RequestMethod.POST, RequestMethod.GET})
// 方法說明
@ApiOperation(value = "刪除學生記錄學生記錄")
// 定義返回值意義
@ApiResponses({
        @ApiResponse(code = 400, message = "服務器內部異常"),
        @ApiResponse(code = 500, message = "權限不足") })
public int del(int id){
    System.out.println("del id = " + id);
    return 1;
}  
複製代碼

結果以下:

這裏寫圖片描述

其它

在測試過程當中,可能出現界面內容沒有被刷新,則可使用 shift + F5 強制刷新

代碼

以上的詳細的代碼見下面 github代碼,請儘可能使用tag v0.22,不要使用master,由於我不能保證master代碼一直不變