微信公衆號:一個優秀的廢人 若有問題或建議,請後臺留言,我會盡力解決你的問題。html
快過年了,不知道大家啥時候放年假,忙不忙。反正我是挺閒的,因此有時間寫 blog。今天給大家帶來 SpringBoot 集成 Swagger2 的教程。前端
Swagger 是一個規範和完整的框架,用於生成、描述、調用和可視化 RESTful 風格的 Web 服務。java
相信剛開始不熟悉 web 開發的時候,你們都有手寫 Api 文檔的時候。而手寫 Api 文檔主要有如下幾個痛點:mysql
這些痛點在先後端分離的大型項目上顯得尤其煩躁。而 Swagger2 的出現剛好能個解決這些痛點。由於 Swagger2 有如下功能:git
首先新建一個 SpringBoot 項目,還不會的參考我這篇舊文—— 如何使用 IDEA 構建 Spring Boot 工程github
構建時,在選擇依賴那一步勾選 Web、LomBok、JPA 和 Mysql 依賴。其中 Mysql 能夠不勾,由於我這裏用於操做實際的數據庫,因此我勾選了。web
生成 SpringBoot 後的 Pom 文件依賴以下:這裏使用的是 2.4.0 的 Swagger2 版本。算法
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.nasus</groupId>
<artifactId>swagger2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>swagger2</name>
<description>Demo project for Swagger2</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
複製代碼
第二步,在 SpringBoot 啓動類(Application)的同級目錄新建一個 Swagger 配置類,注意 Swagger2 配置類必須與項目入口類 Application 位於同一級目錄,不然生成 Api 文檔失敗,代碼以下:spring
package com.nasus;
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.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Project Name:swagger2-demo <br/>
* Package Name:com.nasus <br/>
* Date:2019/1/22 22:52 <br/>
* <b>Description:</b> TODO: 描述該類的做用 <br/>
*
* @author <a href="turodog@foxmail.com">nasus</a><br/>
* Copyright Notice =========================================================
* This file contains proprietary information of Eastcom Technologies Co. Ltd.
* Copying or reproduction without prior written approval is prohibited.
* Copyright (c) 2019 =======================================================
*/
@Configuration
// 啓用 Swagger2
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// 文檔信息對象
.apiInfo(apiInfo())
.select()
// 被註解的包路徑
.apis(RequestHandlerSelectors.basePackage("com.nasus.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 標題
.title("springboot 利用 swagger 構建 API 文檔")
// Api 文檔描述
.description("簡單優雅的 restful 風格,https://blog.csdn.net/turodog/")
.termsOfServiceUrl("https://blog.csdn.net/turodog/")
// 文檔做者信息
.contact(new Contact("陳志遠", "https://github.com/turoDog", "turodog@foxmail.com"))
// 文檔版本
.version("1.0")
.build();
}
}
複製代碼
第三步,配置被註解的 Controller 類,編寫各個接口的請求參數,返回結果,接口描述等等,代碼以下:sql
package com.nasus.controller;
import com.nasus.entity.Student;
import com.nasus.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
/**
* Project Name:swagger2-demo <br/>
* Package Name:com.nasus.controller <br/>
* Date:2019/1/22 22:07 <br/>
* <b>Description:</b> TODO: 描述該類的做用 <br/>
*
* @author <a href="turodog@foxmail.com">nasus</a><br/>
* Copyright Notice =========================================================
* This file contains proprietary information of Eastcom Technologies Co. Ltd.
* Copying or reproduction without prior written approval is prohibited.
* Copyright (c) 2019 =======================================================
*/
@RestController
@RequestMapping("/student")
// @Api:修飾整個類,描述Controller的做用
@Api("StudentController Api 接口文檔")
public class StudentController {
@Autowired
private StudentService studentService;
// @ApiOperation:描述一個類的一個方法,或者說一個接口
@ApiOperation(value="獲取全部學生列表", notes="獲取全部學生列表")
@RequestMapping(value={""}, method= RequestMethod.GET)
public List<Student> getStudent() {
List<Student> list = studentService.findAll();
return list;
}
@ApiOperation(value="添加學生信息", notes="添加學生信息")
// @ApiImplicitParam:一個請求參數
@ApiImplicitParam(name = "student", value = "學生信息詳細實體", required = true, dataType = "Student")
@PostMapping("/save")
public Student save(@RequestBody Student student){
return studentService.save(student);
}
@ApiOperation(value="獲學生信息", notes="根據url的id來獲取學生詳細信息")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer",paramType = "path")
@GetMapping("/{id}")
public Student findById(@PathVariable("id") Integer id){
return studentService.findById(id);
}
@ApiOperation(value="刪除學生", notes="根據url的id來指定刪除的學生")
@ApiImplicitParam(name = "id", value = "學生ID", required = true, dataType = "Integer",paramType = "path")
@DeleteMapping("/{id}")
public String deleteById(@PathVariable("id") Integer id){
studentService.delete(id);
return "success";
}
@ApiOperation(value="更新學生信息", notes="根據url的id來指定更新學生信息")
// @ApiImplicitParams:多個請求參數
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "學生ID", required = true, dataType = "Integer",paramType = "path"),
@ApiImplicitParam(name = "student", value = "學生實體student", required = true, dataType = "Student")
})
@PutMapping(value="/{id}")
public String updateStudent(@PathVariable Integer id, @RequestBody Student student) {
Student oldStudent = this.findById(id);
oldStudent.setId(student.getId());
oldStudent.setName(student.getName());
oldStudent.setAge(student.getAge());
studentService.save(oldStudent);
return "success";
}
// 使用該註解忽略這個API
@ApiIgnore
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
}
複製代碼
第四步,啓動項目,訪問 http://localhost:8080/swagger-ui.html 地址,結果以下圖:
@ApiOperation:用在方法上,說明方法的做用
1.value: 表示接口名稱
2.notes: 表示接口詳細描述
@ApiImplicitParams:用在方法上包含一組參數說明
@ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求參數的各個方面
1.paramType:參數位置
2.header 對應註解:@RequestHeader
3.query 對應註解:@RequestParam
4.path 對應註解: @PathVariable
5.body 對應註解: @RequestBody
6.name:參數名
7.dataType:參數類型
8.required:參數是否必須傳
9.value:參數的描述
10.defaultValue:參數的默認值
@ApiResponses:用於表示一組響應
@ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息
1.code:狀態碼
2.message:返回自定義信息
3.response:拋出異常的類
@ApiIgnore: 表示該接口函數不對swagger2開放展現
@Api:修飾整個類,描述Controller的做用
@ApiParam:單個參數描述
@ApiModel:用對象來接收參數
@ApiProperty:用對象接收參數時,描述對象的一個字段
@ApiIgnore:使用該註解忽略這個API
@ApiError :發生錯誤返回的信息
複製代碼
@ApiImplicitParam 註解下的 paramType 屬性,會影響接口的測試,若是設置的屬性跟spring 的註解對應不上,會獲取不到參數,例如 paramType=path ,函數內卻使用@RequestParam 註解,這樣,可能會獲取不到傳遞進來的參數,須要按照上面進行對應,將 @RequestParam 註解改成 @PathVariable 才能獲取到對應的參數。
以上就是我對 Swagger2 的理解與使用,以上只是教你們入門 Swagger2 ,想要深刻使用仍是但願自行查閱官方文檔。最後,對 Python 、Java 感興趣請長按二維碼關注一波,我會努力帶給大家價值,若是以爲本文對你哪怕有一丁點幫助,請幫忙點好看,讓更多人知道。
另外,關注以後在發送 1024 可領取免費學習資料。資料內容詳情請看這篇舊文:Python、C++、Java、Linux、Go、前端、算法資料分享