在SpringBoot項目中的使用Swagger的方法示例
一. 首先Swagger是什么?
Swagger 是一個規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風格的 Web 服務??傮w目標是使客戶端和文件系統(tǒng)作為服務器以同樣的速度來更新。文件的方法,參數(shù)和模型緊密集成到服務器端的代碼,允許API來始終保持同步。Swagger官方API文檔:https://swagger.io/
作用:
1. 接口的文檔在線自動生成。
2. 功能測試。
Swagger的主見介紹:
Swagger Codegen: 通過Codegen 可以將描述文件生成html格式和cwiki形式的接口文檔,同時也能生成多鐘語言的服務端和客戶端的代碼。支持通過jar包,docker,node等方式在本地化執(zhí)行生成。也可以在后面的Swagger Editor中在線生成。
Swagger UI: 提供了一個可視化的UI頁面展示描述文件。接口的調(diào)用方、測試、項目經(jīng)理等都可以在該頁面中對相關接口進行查閱和做一些簡單的接口請求。該項目支持在線導入描述文件和本地部署UI項目。
Swagger Editor: 類似于markendown編輯器的編輯Swagger描述文件的編輯器,該編輯支持實時預覽描述文件的更新效果。也提供了在線編輯器和本地部署編輯器兩種方式。
Swagger Inspector: 感覺和postman差不多,是一個可以對接口進行測試的在線版的postman。比在Swagger UI里面做接口請求,會返回更多的信息,也會保存你請求的實際請求參數(shù)等數(shù)據(jù)。
Swagger Hub: 集成了上面所有項目的各個功能,你可以以項目和版本為單位,將你的描述文件上傳到Swagger Hub中。在Swagger Hub中可以完成上面項目的所有工作,需要注冊賬號,分免費版和收費版。
PS:
Springfox Swagger: Spring 基于 swagger 規(guī)范,可以將基于 SpringMVC 和 Spring Boot 項目的項目代碼,自動生成 JSON 格式的描述文件。本身不是屬于 Swagger 官網(wǎng)提供的,在這里列出來做個說明,方便后面作一個使用的展開。
二. Swagger UI的使用:
Swagger注解解釋:
@Api:請求類的說明
@Api:放在 請求的類上,與 @Controller 并列,說明類的作用,如用戶模塊,訂單類等。
tags="說明該類的作用"
value="該參數(shù)沒什么意義,所以不需要配置"
常用注解:
- @Api()用于類;
表示標識這個類是swagger的資源
- @ApiOperation()用于方法;
表示一個http請求的操作
- @ApiParam()用于方法,參數(shù),字段說明;
表示對參數(shù)的添加元數(shù)據(jù)(說明或是否必填等)
- @ApiModel()用于類
表示對類進行說明,用于參數(shù)用實體類接收
- @ApiModelProperty()用于方法,字段
表示對model屬性的說明或者數(shù)據(jù)操作更改
- @ApiIgnore()用于類,方法,方法參數(shù)
表示這個方法或者類被忽略
- @ApiImplicitParam() 用于方法
表示單獨的請求參數(shù)
- @ApiImplicitParams() 用于方法
包含多個 @ApiImplicitParam
(1). @Api: 請求類的說明
@Api:放在 請求的類上,與 @Controller 并列,說明類的作用,如用戶模塊,訂單類等。 tags="說明該類的作用" value="描述該類作用" [推薦用這個] @Api 其它屬性配置: 屬性名稱 備注 value url的路徑值 tags 如果設置這個值、value的值會被覆蓋 description 對api資源的描述 basePath 基本路徑 position 如果配置多個Api 想改變顯示的順序位置 produces 如, “application/json, application/xml” consumes 如, “application/json, application/xml” protocols 協(xié)議類型,如: http, https, ws, wss. authorizations 高級特性認證時配置 hidden 配置為true ,將在文檔中隱藏
(2). @ApiOperation:方法的說明
@ApiOperation:"用在請求的方法上,說明方法的作用" value="說明方法的作用" notes="方法的備注說明"
(3). @ApiImplicitParams、@ApiImplicitParam:方法參數(shù)的說明
@ApiImplicitParams:用在請求的方法上,包含一組參數(shù)說明
@ApiImplicitParam:對單個參數(shù)的說明
name:參數(shù)名
value:參數(shù)的漢字說明、解釋
required:參數(shù)是否必須傳
paramType:參數(shù)放在哪個地方
· header --> 請求參數(shù)的獲取:@RequestHeader
· query --> 請求參數(shù)的獲?。篅RequestParam
· path(用于restful接口)--> 請求參數(shù)的獲取:@PathVariable
· body(請求體)--> @RequestBody User user
· form(普通表單提交)
dataType:參數(shù)類型,默認String,其它值dataType="Integer"
defaultValue:參數(shù)的默認值
示例:
@Api(tags="用戶模塊") @Controller public class UserController { @ApiOperation(value="用戶登錄",notes="隨邊說點啥") @ApiImplicitParams({ @ApiImplicitParam(name="mobile",value="手機號",required=true,paramType="form"), @ApiImplicitParam(name="password",value="密碼",required=true,paramType="form"), @ApiImplicitParam(name="age",value="年齡",required=true,paramType="form",dataType="Integer") }) @PostMapping("/login") public JsonResult login(@RequestParam String mobile, @RequestParam String password, @RequestParam Integer age){ //... return JsonResult.ok(map); } }
(4). @ApiResponses、@ApiResponse:方法返回值的說明
@ApiResponses:方法返回對象的說明 @ApiResponse:每個參數(shù)的說明 code:數(shù)字,例如400 message:信息,例如"請求參數(shù)沒填好" response:拋出異常的類
(5). @ApiModel:用于JavaBean上面,表示一個JavaBean(如:響應數(shù)據(jù))的信息
@ApiModel:用于JavaBean的類上面,表示此 JavaBean 整體的信息 (這種一般用在post創(chuàng)建的時候,使用 @RequestBody 這樣的場景, 請求參數(shù)無法使用 @ApiImplicitParam 注解進行描述的時候 )
(6). @ApiModelProperty:用在JavaBean類的屬性上面,說明屬性的含義
@ApiModel(description= "返回響應數(shù)據(jù)") public class RestMessage implements Serializable{ @ApiModelProperty(value = "是否成功") private boolean success=true; @ApiModelProperty(value = "返回對象") private Object data; @ApiModelProperty(value = "錯誤編號") private Integer errCode; @ApiModelProperty(value = "錯誤信息") private String message; /* getter/setter 略*/ }
三. Swagger整合SpringBoot
1. Pom依賴:
<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>
2. 配置類:
package com.zhiyou100.configBeans; 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; /** * @Author ZhengZiXuan * @Desc */ @Configuration // @Configuration注解,讓Spring來加載該類配置。 @EnableSwagger2 //@EnableSwagger2注解來啟用Swagger2 public class SwaggerConfigBean { /** * 創(chuàng)建API應用 * apiInfo() 增加API相關信息 * 通過select()函數(shù)返回一個ApiSelectorBuilder實例,用來控制哪些接口暴露給Swagger來展現(xiàn), * 本例采用指定掃描的包路徑來定義指定要建立API的目錄。 * * @return */ @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.zhiyou100.controller")) .paths(PathSelectors.any()) .build(); } /** * 創(chuàng)建該API的基本信息(這些基本信息會展現(xiàn)在文檔頁面中) * 訪問地址:http://項目實際地址/swagger-ui.html * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("使用Swagger2 構建RESTful APIS - 廢物") .description("廢物 - Swagger使用演示") .termsOfServiceUrl("www.zzxBIuBIuBIu.com") .version("1.0") .build(); } }
3. 正常的Controller再加Swagger注解:
package com.zhiyou100.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * @Author ZhengZiXuan * @Desc */ @Controller @Api("測試Swagger 的Controller類") public class TestController { @ApiOperation(value="根據(jù)id查詢名字",notes = "備注:無") @ApiImplicitParam(name = "id",value = "用戶id",required = true, paramType = "query",dataType = "Integer") @RequestMapping("/getNameById") @ResponseBody public String getNameById(int id){ return "張三"; } }
4.啟動測試:
http://localhost:8080/swagger-ui.html
四. 訪問404Bug的解決方法
Swagger UI 界面介紹:
五. Model對象增刪改查演示
對User類實現(xiàn)增刪改查,生成api文檔
package com.zhiyou100.model; /** * @Author ZhengZiXuan * @Date 2021/05/10 * @Desc */ public class User { private int id; private String name; private String password; @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}'; } public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public User(int id, String name, String password) { this.id = id; this.name = name; this.password = password; } }
package com.zhiyou100.controller; import com.zhiyou100.model.User; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * @Author ZhengZiXuan * @Date 2021/05/10 * @Desc 有點BUG 就是list集合中的增刪改 */ @RestController @Api("User類的增刪改查API") public class UserController { ArrayList<User> users = null; public UserController(){ users = new ArrayList<>(); users.add(new User(1,"張三","123")); users.add(new User(2,"李四","1234")); users.add(new User(3,"王五","12345")); System.out.println("init users "+users); } /** * 根據(jù)id查User */ @ApiOperation("根據(jù)id查用戶") @ApiImplicitParam(name = "id",value = "用戶id", required = true,paramType = "path", dataType = "Integer") @RequestMapping(value="/user/get/{id}",method = RequestMethod.GET) public User getUserById(@PathVariable("id") Integer id){ System.out.println("getUserById id: "+id); if (id != null){ if (id>0 && id <4){ User user = users.get(id); System.out.println("getUserById User: "+user); return user; } } return null; } /** * 查全部user */ @ApiOperation("查詢?nèi)坑脩?) @RequestMapping(value="/user/get",method = RequestMethod.GET) public List<User> getAllUser(){ System.out.println("getAllUser"); return users; } /** * 添加User */ @ApiOperation("添加用戶") @ApiImplicitParam(name="user",value = "用戶對象",paramType = "body",dataType = "User") @RequestMapping(value="/user/add",method = RequestMethod.POST) public User addUser(@RequestBody User user){ System.out.println("addUser User:"+user); if (user == null || user.getId() == 0){ return null; } users.add(user); return user; } /** * 刪除User */ @ApiOperation("根據(jù)id刪除用戶") @ApiImplicitParam(name = "id",value = "用戶id", required = true,paramType = "path", dataType = "Integer") @RequestMapping(value="/user/delete/{id}",method = RequestMethod.DELETE) public boolean delUserById(@PathVariable("id") Integer id){ System.out.println("delUserById id:"+id); if (id != null){ users.remove(id); return true; } return false; } /** * 更新User */ @ApiOperation("根據(jù)id更新用戶") @ApiImplicitParams({ @ApiImplicitParam(name = "id",value = "用戶id", required = true,paramType = "path", dataType = "Integer"), @ApiImplicitParam(name = "user",value = "用戶對象", required = true,paramType = "body", dataType = "User")}) @RequestMapping(value="/user/update/{id}",method = RequestMethod.PUT) public boolean UpdateUserById(@PathVariable("id") Integer id,@RequestBody User user){ System.out.println("UpdateUserById id:"+id+" , User:"+user); if (id != null && user != null){ users.add(id,user); return true; } return false; } }
1. 查詢?nèi)?
2. 根據(jù)id查:
3. 添加用戶:
4.更新用戶:
5. 刪除用戶:
到此這篇關于在SpringBoot項目中的使用Swagger的方法示例的文章就介紹到這了,更多相關SpringBoot使用Swagger內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring MVC-@RequestMapping注解詳解
@RequestMapping注解的作用,就是將請求和處理請求的控制器方法關聯(lián)起來,建立映射關系。這篇文章主要給大家介紹了關于SpringMVC中@RequestMapping注解用法,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-04-04基于Spring + Spring MVC + Mybatis 高性能web構建實例詳解
這篇文章主要介紹了基于Spring + Spring MVC + Mybatis 高性能web構建實例詳解,需要的朋友可以參考下2017-04-04