在開發(fā)過程中,為了實現(xiàn)前后端高效的溝通,通常需要提供相關的接口文檔炸渡。
Swagger2可以輕松的整合到SpringBoot中瓶逃,并與SpringMVC程序配合組織出強大RESTful API文檔束铭。它既可以減少我們創(chuàng)建文檔的工作量,也可以讓我們在修改代碼邏輯的同時修改文檔說明厢绝。此外Swagger2也提供了強大的頁面測試功能來調(diào)試每個RESTful API契沫。
本文主要介紹Spring Boot 2.0 與 Swagger2的整合。
一昔汉、swagger 注解
@Api:用在請求的類上懈万,表示對類的說明
tags="說明該類的作用,可以在UI界面上看到的注解"
value="該參數(shù)沒什么意義,在UI界面上也看到会通,所以不需要配置"
@ApiOperation:用在請求的方法上口予,說明方法的用途、作用
value="說明方法的用途涕侈、作用"
notes="方法的備注說明"
@ApiImplicitParams:用在請求的方法上苹威,表示一組參數(shù)說明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個請求參數(shù)的各個方面
name:參數(shù)名
value:參數(shù)的漢字說明驾凶、解釋
required:參數(shù)是否必須傳
paramType:參數(shù)放在哪個地方
· header --> 請求參數(shù)的獲妊栏Α:@RequestHeader
· query --> 請求參數(shù)的獲取:@RequestParam
· path(用于restful接口)--> 請求參數(shù)的獲鹊魑ァ:@PathVariable
· body(不常用)
· form(不常用)
dataType:參數(shù)類型窟哺,默認String,其它值dataType="Integer"
defaultValue:參數(shù)的默認值
@ApiResponses:用在請求的方法上技肩,表示一組響應
@ApiResponse:用在@ApiResponses中且轨,一般用于表達一個錯誤的響應信息
code:數(shù)字,例如400
message:信息虚婿,例如"請求參數(shù)沒填好"
response:拋出異常的類
@ApiModel:用于類上旋奢,表示一組數(shù)據(jù)的信息
(這種一般用在post創(chuàng)建的時候,使用@RequestBody這樣的場景然痊,
請求參數(shù)無法使用@ApiImplicitParam注解進行描述的時候)
@ApiModelProperty:用在屬性上至朗,描述屬性
二、添加依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
三剧浸、配置Swagger
package pers.simon.boot.validator.config;
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.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* swagger2 配置
*
* @author simon
* @date 2019/12/12 13:57
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 實例化一個 Docket Bean
* <p></p>
* <b>
* 這個Bean中锹引,配置映射路徑和要掃描的接口的位置,在apiInfo中唆香,主要配置一下Swagger2文檔網(wǎng)站的信息嫌变,例如網(wǎng)站的title,網(wǎng)站的描述躬它,聯(lián)系人的信息腾啥,使用的協(xié)議等等
* </b>
*
* @return Docket Bean
*/
@Bean
public Docket createDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")//默認請求都是以 / 根路徑開始,如果我們的應用不是部署在根路徑冯吓,比如以/validator部署赏参,則可以通過一下方式設置請求的統(tǒng)一前綴
.select()
.apis(RequestHandlerSelectors.basePackage("pers.simon.boot.validator.controller"))//
.paths(PathSelectors.any())
.build()
.apiInfo(new ApiInfoBuilder()
.title("Spring Boot 參數(shù)校驗")
.description("使用 validator 對入?yún)⑦M行校驗梆造。包含自定義規(guī)則校驗匾鸥,分組校驗膏斤,全局異常處理等")
.version("1.0.0")
.contact(new Contact("simon", "www.baidu.com", "simon@126.com"))
.license("The Apache License")
.licenseUrl("www.baidu.com")
.build()
);
}
}
四状共、接口
package pers.simon.boot.validator.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import pers.simon.boot.validator.annotate.Create;
import pers.simon.boot.validator.annotate.Update;
import pers.simon.boot.validator.po.UserVo;
import pers.simon.boot.validator.utils.JsonResult;
import javax.validation.constraints.NotEmpty;
/**
*
* @author simon
* @date 2019/12/10 10:39
*/
@Api(tags = "用戶管理")
@RestController
@Validated
public class UserController {
@ApiOperation("添加用戶")
@PostMapping("/user")
@ApiImplicitParam(name = "userVo", value = "用戶信息表單", required = true, dataType = "UserVo")
public JsonResult saveUser(@RequestBody @Validated(Create.class) UserVo userVo){
return JsonResult.success(userVo);
}
@ApiOperation("修改用戶")
@ApiImplicitParam(name = "userVo", value = "用戶信息表單", required = true, dataType = "UserVo")
@PutMapping("/user")
public JsonResult updateUser(@RequestBody @Validated(Update.class) UserVo userVo){
return JsonResult.success(userVo);
}
@ApiOperation("注銷用戶")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId",value = "用戶ID",defaultValue = "",required = true),
@ApiImplicitParam(name = "deptId",value = "部門ID",defaultValue = "",required = true)
})
@PatchMapping("/user")
public JsonResult disableUser(@NotEmpty(message = "用戶ID不能為空")String userId, @NotEmpty(message = "所屬部門ID不能為空")String deptId){
return JsonResult.success(userId);
}
}
入?yún)serVo
package pers.simon.boot.validator.po;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import pers.simon.boot.validator.annotate.Create;
import pers.simon.boot.validator.annotate.IdCard;
import pers.simon.boot.validator.annotate.Update;
import javax.validation.constraints.*;
import java.util.Date;
/**
* @author simon
* @date 2019/12/10 10:28
*/
@ApiModel(description = "用戶信息表單")
@Data
public class UserVo {
@ApiModelProperty(value = "用戶ID", name = "userId", required = true, example = "123")
@Null(message = "用戶ID必須為空",groups = Create.class)
@NotBlank(message = "用戶ID不能為空",groups = Update.class)
private String userId;
@ApiModelProperty(value = "用戶名稱", name = "userName", required = true, example = "admin")
@NotBlank(message = "用戶名不能為空")
private String userName;
@ApiModelProperty(value = "生日", name = "birthday", required = true, example = "2019-11-02")
@Past(message = "生日必須為過去日期")
@NotNull(message = "生日不能為空")
private Date birthday;
@ApiModelProperty(value = "年齡", name = "age", required = true, example = "11", dataType = "int")
@Min(value = 10,message = "年齡必須大于10")
@Max(value = 30,message = "年齡必須小于30")
@NotNull(message = "年齡不能為空")
private Integer age;
@ApiModelProperty(value = "郵箱", name = "email", required = true, example = "11@qq.com")
@NotBlank(message = "郵箱不能為空")
@Email(message = "郵箱格式錯誤")
private String email;
@ApiModelProperty(value = "手機號", name = "phone", required = true, example = "12345678900")
@NotNull(message = "手機號不能為空")
@NotBlank(message = "手機號不能為空")
@Pattern(regexp ="^[1][3,4,5,6,7,8,9][0-9]{9}$", message = "手機號格式有誤")
@Max(value = 11,message = "手機號只能為11位")
@Min(value = 11,message = "手機號只能為11位")
private String phone;
@ApiModelProperty(value = "身份證號", name = "idCard", required = true, example = "12345678900")
@NotBlank(message = "身份證不能為空")
@IdCard(message = "身份證不合法")
private String idCard;
}
六冻河、測試
訪問:http://localhost:8080/swagger-ui.html
2aa6d12ee2d2ad060698cce87e45a6c.png