什么是Swagger2
編寫和維護(hù)接口文檔是每個(gè)程序員的職責(zé),根據(jù) Swagger2 可以快速幫助我們編寫最新的API接口文檔,再也不用擔(dān)心開會(huì)前仍忙于整理各種資料了,間接提升了團(tuán)隊(duì)開發(fā)的溝通效率。常用注解swagger通過注解表明該接口會(huì)生成文檔,包括接口名、請(qǐng)求方法、參數(shù)、返回信息的等等。
配置
- 首先需要在pom.xml添加Swagger2所需要的依賴。
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
-
添加Swagger2的配置文件 config -->SwaggerConfig.java
1.添加@EnableSwagger2
@EnableSwagger2.png
2.配置創(chuàng)建文檔API信息
文檔api信息.png -
注意:此處的params為header中的token令牌,并非所有的請(qǐng)求都需要token參數(shù)。
3.配置Info信息info.png
效果:
配置信息后的效果.png
4.關(guān)于http請(qǐng)求狀態(tài)碼信息的配置
請(qǐng)求狀態(tài)碼信息.png
效果:
狀態(tài)碼.png
package com.wsy.mybatis_plus_demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(){
//================== 需要的參數(shù)START========================
List<Parameter> pars = new ArrayList<>();
ParameterBuilder token = new ParameterBuilder();
token.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(token.build());
// ==================== 需要的參數(shù) END ====================
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(pars)//全局非必填參數(shù)
.globalResponseMessage(RequestMethod.GET,customerResponseMessage())
.globalResponseMessage(RequestMethod.GET,customerResponseMessage())
.apiInfo(apiInfo())
.select()
//項(xiàng)目包所在的controller
.apis(RequestHandlerSelectors.basePackage("com.wsy.mybatis_plus_demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("零食商販--基礎(chǔ)數(shù)據(jù)API說明文檔")
.description("2019-07-20 開始項(xiàng)目")
.contact(new Contact("shine_rainbow","http://github.com/shinefairy","804886201@qq.com"))
//.termsOfServiceUrl("localhost:8080/")
.version("1.0")
.build();
}
private List<ResponseMessage> customerResponseMessage(){
List<ResponseMessage> list = new ArrayList<>();
list.add(new ResponseMessageBuilder().code(200).message("請(qǐng)求成功").build());
list.add(new ResponseMessageBuilder().code(201).message("資源創(chuàng)建成功").build());
list.add(new ResponseMessageBuilder().code(204).message("服務(wù)器成功處理了請(qǐng)求,但不需要返回任何實(shí)體內(nèi)容").build());
list.add(new ResponseMessageBuilder().code(400).message("請(qǐng)求失敗,具體查看返回業(yè)務(wù)狀態(tài)碼與對(duì)應(yīng)消息").build());
list.add(new ResponseMessageBuilder().code(401).message("請(qǐng)求失敗,未經(jīng)過身份認(rèn)證").build());
list.add(new ResponseMessageBuilder().code(405).message("請(qǐng)求方法不支持").build());
list.add(new ResponseMessageBuilder().code(415).message("請(qǐng)求媒體類型不支持").build());
list.add(new ResponseMessageBuilder().code(500).message("服務(wù)器遇到了一個(gè)未曾預(yù)料的狀況,導(dǎo)致了它無法完成對(duì)請(qǐng)求的處理").build());
list.add(new ResponseMessageBuilder().code(503).message("服務(wù)器當(dāng)前無法處理請(qǐng)求,這個(gè)狀況是臨時(shí)的,并且將在一段時(shí)間以后恢復(fù)").build());
return list;
}
}
-
Controller中添加相關(guān)注解
1.添加@Api注解在Controller
@Api.png- @Api:用在請(qǐng)求的類上,說明該類的作用
@Api:用在請(qǐng)求的類上,說明該類的作用
tags="說明該類的作用"
value="該參數(shù)沒什么意義,所以不需要配置"
參數(shù)說明
| 注解 | 參數(shù) | 參數(shù)說明 |
|---|---|---|
| @api | tags | 說明該類的作用,可以在UI界面上看到的注解 |
| @api | value | 該參數(shù)沒什么意義,在UI界面上也看到,所以不需要配置 |
實(shí)例:@Api(tags="APP用戶注冊(cè)Controller")
2.添加@ApiOperation等注解在請(qǐng)求方法上

- @ApiOperation:用在請(qǐng)求的方法上,說明方法的作用
@ApiOperation:"用在請(qǐng)求的方法上,說明方法的作用"
value="說明方法的作用"
notes="方法的備注說明"
參數(shù)說明
| 注解 | 參數(shù) | 參數(shù)說明 |
|---|---|---|
| @api | value | 說明方法的作用 |
| @api | notes | 方法的備注說明 |
實(shí)例:@ApiOperation(value="用戶注冊(cè)",notes="手機(jī)號(hào)、密碼都是必輸項(xiàng),年齡隨邊填,但必須是數(shù)字")
- @ApiImplicitParams:用在請(qǐng)求的方法上,包含一組參數(shù)說明
@ApiImplicitParams:用在請(qǐng)求的方法上,包含一組參數(shù)說明
@ApiImplicitParam:用在 @ApiImplicitParams 注解中,指定一個(gè)請(qǐng)求參數(shù)的配置信息
name:參數(shù)名
value:參數(shù)的漢字說明、解釋
required:參數(shù)是否必須傳
paramType:參數(shù)放在哪個(gè)地方
· header --> 請(qǐng)求參數(shù)的獲?。篅RequestHeader
· query --> 請(qǐng)求參數(shù)的獲取:@RequestParam
· path(用于restful接口)--> 請(qǐng)求參數(shù)的獲?。篅PathVariable
· body(不常用)
· form(不常用)
dataType:參數(shù)類型,默認(rèn)String,其它值dataType="Integer"
defaultValue:參數(shù)的默認(rèn)值
示例:
@ApiImplicitParams({
@ApiImplicitParam(name="mobile",value="手機(jī)號(hào)",required=true,paramType="form"),
@ApiImplicitParam(name="password",value="密碼",required=true,paramType="form"),
@ApiImplicitParam(name="age",value="年齡",required=true,paramType="form",dataType="Integer")
})
- @ApiResponses:用于請(qǐng)求的方法上,表示一組響應(yīng)
@ApiResponses:用于請(qǐng)求的方法上,表示一組響應(yīng)
@ApiResponse:用在@ApiResponses中,一般用于表達(dá)一個(gè)錯(cuò)誤的響應(yīng)信息
code:數(shù)字,例如400
message:信息,例如"請(qǐng)求參數(shù)沒填好"
response:拋出異常的類
@ApiOperation(value = "select1請(qǐng)求",notes = "多個(gè)參數(shù),多種的查詢參數(shù)類型")
@ApiResponses({
@ApiResponse(code=400,message="請(qǐng)求參數(shù)沒填好"),
@ApiResponse(code=404,message="請(qǐng)求路徑?jīng)]有或頁(yè)面跳轉(zhuǎn)路徑不對(duì)")
})
- @ApiModel:用于響應(yīng)類上,表示一個(gè)返回響應(yīng)數(shù)據(jù)的信息
@ApiModel:用于響應(yīng)類上,表示一個(gè)返回響應(yīng)數(shù)據(jù)的信息
(這種一般用在post創(chuàng)建的時(shí)候,使用@RequestBody這樣的場(chǎng)景,
請(qǐng)求參數(shù)無法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)
@ApiModelProperty:用在屬性上,描述響應(yīng)類的屬性
示例:
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
@ApiModel(description= "返回響應(yīng)數(shù)據(jù)")
public class RestMessage implements Serializable{
@ApiModelProperty(value = "是否成功")
private boolean success=true;
@ApiModelProperty(value = "返回對(duì)象")
private Object data;
@ApiModelProperty(value = "錯(cuò)誤編號(hào)")
private Integer errCode;
@ApiModelProperty(value = "錯(cuò)誤信息")
private String message;
/* getter/setter */
}
package com.wsy.mybatis_plus_demo.controller;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wsy.mybatis_plus_demo.entity.User;
import com.wsy.mybatis_plus_demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author shine
* @since 2019-07-19
*/
@Api(tags = "用戶接口")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 根據(jù)id查找用戶
*/
@ApiOperation(value = "獲取用戶詳細(xì)信息",notes = "根據(jù)url傳來的id獲取用戶對(duì)象")
@ApiImplicitParam(name = "id",value = "用戶id",required = true,dataType = "Integer",paramType = "path")
@GetMapping(value = "/{id}")
public User getUserById(@PathVariable(value = "id") Integer id){
User user = userService.getById(id);
return ObjectUtils.isNotEmpty(user)?user:null;
}
}
效果:







