国产成人精品18p,天天干成人网,无码专区狠狠躁天天躁,美女脱精光隐私扒开免费观看

在SpringBoot項目中的使用Swagger的方法示例

發(fā)布時(shí)間:2021-07-06 11:13 來(lái)源:腳本之家 閱讀:0 作者:小鄭要做干飯人 欄目: 開(kāi)發(fā)技術(shù)

目錄

      一. 首先Swagger是什么?

      Swagger 是一個(gè)規范和完整的框架,用于生成、描述、調用和可視化 RESTful 風(fēng)格的 Web 服務(wù)??傮w目標是使客戶(hù)端和文件系統作為服務(wù)器以同樣的速度來(lái)更新。文件的方法,參數和模型緊密集成到服務(wù)器端的代碼,允許API來(lái)始終保持同步。Swagger官方API文檔:

      作用:
        1. 接口的文檔在線(xiàn)自動(dòng)生成。
        2. 功能測試。

      Swagger的主見(jiàn)介紹:

         Swagger Codegen: 通過(guò)Codegen 可以將描述文件生成html格式和cwiki形式的接口文檔,同時(shí)也能生成多鐘語(yǔ)言的服務(wù)端和客戶(hù)端的代碼。支持通過(guò)jar包,docker,node等方式在本地化執行生成。也可以在后面的Swagger Editor中在線(xiàn)生成。

        Swagger UI: 提供了一個(gè)可視化的UI頁(yè)面展示描述文件。接口的調用方、測試、項目經(jīng)理等都可以在該頁(yè)面中對相關(guān)接口進(jìn)行查閱和做一些簡(jiǎn)單的接口請求。該項目支持在線(xiàn)導入描述文件和本地部署UI項目。

        Swagger Editor: 類(lèi)似于markendown編輯器的編輯Swagger描述文件的編輯器,該編輯支持實(shí)時(shí)預覽描述文件的更新效果。也提供了在線(xiàn)編輯器和本地部署編輯器兩種方式。

        Swagger Inspector: 感覺(jué)和postman差不多,是一個(gè)可以對接口進(jìn)行測試的在線(xiàn)版的postman。比在Swagger UI里面做接口請求,會(huì )返回更多的信息,也會(huì )保存你請求的實(shí)際請求參數等數據。

        Swagger Hub: 集成了上面所有項目的各個(gè)功能,你可以以項目和版本為單位,將你的描述文件上傳到Swagger Hub中。在Swagger Hub中可以完成上面項目的所有工作,需要注冊賬號,分免費版和收費版。

      PS:
        Springfox Swagger: Spring 基于 swagger 規范,可以將基于 SpringMVC 和 Spring Boot 項目的項目代碼,自動(dòng)生成 JSON 格式的描述文件。本身不是屬于 Swagger 官網(wǎng)提供的,在這里列出來(lái)做個(gè)說(shuō)明,方便后面作一個(gè)使用的展開(kāi)。

      二. Swagger UI的使用:

      Swagger注解解釋:

      @Api:請求類(lèi)的說(shuō)明
      @Api:放在 請求的類(lèi)上,與 @Controller 并列,說(shuō)明類(lèi)的作用,如用戶(hù)模塊,訂單類(lèi)等。
      tags="說(shuō)明該類(lèi)的作用"
      value="該參數沒(méi)什么意義,所以不需要配置"

      常用注解:
      - @Api()用于類(lèi);
      表示標識這個(gè)類(lèi)是swagger的資源
      - @ApiOperation()用于方法;
      表示一個(gè)http請求的操作
      - @ApiParam()用于方法,參數,字段說(shuō)明;
      表示對參數的添加元數據(說(shuō)明或是否必填等)
      - @ApiModel()用于類(lèi)
      表示對類(lèi)進(jìn)行說(shuō)明,用于參數用實(shí)體類(lèi)接收
      - @ApiModelProperty()用于方法,字段
      表示對model屬性的說(shuō)明或者數據操作更改
      - @ApiIgnore()用于類(lèi),方法,方法參數
      表示這個(gè)方法或者類(lèi)被忽略
      - @ApiImplicitParam() 用于方法
      表示單獨的請求參數
      - @ApiImplicitParams() 用于方法
      包含多個(gè) @ApiImplicitParam

      (1). @Api: 請求類(lèi)的說(shuō)明

      @Api:放在 請求的類(lèi)上,與 @Controller 并列,說(shuō)明類(lèi)的作用,如用戶(hù)模塊,訂單類(lèi)等。
      tags="說(shuō)明該類(lèi)的作用"
      value="描述該類(lèi)作用" [推薦用這個(gè)]
      
      @Api 其它屬性配置:
      
      屬性名稱(chēng) 備注
      value url的路徑值
      tags 如果設置這個(gè)值、value的值會(huì )被覆蓋
      description 對api資源的描述
      basePath 基本路徑
      position 如果配置多個(gè)Api 想改變顯示的順序位置
      produces 如, “application/json, application/xml”
      consumes 如, “application/json, application/xml”
      protocols 協(xié)議類(lèi)型,如: http, https, ws, wss.
      authorizations 高級特性認證時(shí)配置
      hidden 配置為true ,將在文檔中隱藏
      
      
      

      (2). @ApiOperation:方法的說(shuō)明

      @ApiOperation:"用在請求的方法上,說(shuō)明方法的作用"
      	  value="說(shuō)明方法的作用"
      	  notes="方法的備注說(shuō)明"
      

      (3). @ApiImplicitParams、@ApiImplicitParam:方法參數的說(shuō)明

      @ApiImplicitParams:用在請求的方法上,包含一組參數說(shuō)明
      @ApiImplicitParam:對單個(gè)參數的說(shuō)明
      name:參數名
      value:參數的漢字說(shuō)明、解釋
      required:參數是否必須傳
      paramType:參數放在哪個(gè)地方
      · header --> 請求參數的獲?。篅RequestHeader
      · query --> 請求參數的獲?。篅RequestParam
      · path(用于restful接口)--> 請求參數的獲?。篅PathVariable
      · body(請求體)--> @RequestBody User user
      · form(普通表單提交)
      dataType:參數類(lèi)型,默認String,其它值dataType="Integer"
      defaultValue:參數的默認值

      示例:

      @Api(tags="用戶(hù)模塊")
      @Controller
      public class UserController {
      
      	@ApiOperation(value="用戶(hù)登錄",notes="隨邊說(shuō)點(diǎn)啥")
      	@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:方法返回值的說(shuō)明

      @ApiResponses:方法返回對象的說(shuō)明
      	@ApiResponse:每個(gè)參數的說(shuō)明
      	    code:數字,例如400
      	    message:信息,例如"請求參數沒(méi)填好"
      	    response:拋出異常的類(lèi)

      (5). @ApiModel:用于JavaBean上面,表示一個(gè)JavaBean(如:響應數據)的信息

      @ApiModel:用于JavaBean的類(lèi)上面,表示此 JavaBean 整體的信息
      			(這種一般用在post創(chuàng  )建的時(shí)候,使用 @RequestBody 這樣的場(chǎng)景,
      			請求參數無(wú)法使用 @ApiImplicitParam 注解進(jìn)行描述的時(shí)候 )

      (6). @ApiModelProperty:用在JavaBean類(lèi)的屬性上面,說(shuō)明屬性的含義

      @ApiModel(description= "返回響應數據")
      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依賴(lài):

      <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. 配置類(lèi):

      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來(lái)加載該類(lèi)配置。
      @EnableSwagger2 //@EnableSwagger2注解來(lái)啟用Swagger2
      public class SwaggerConfigBean {
          /**
           * 創(chuàng  )建API應用
           * apiInfo() 增加API相關(guān)信息
           * 通過(guò)select()函數返回一個(gè)ApiSelectorBuilder實(shí)例,用來(lái)控制哪些接口暴露給Swagger來(lái)展現,
           * 本例采用指定掃描的包路徑來(lái)定義指定要建立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的基本信息(這些基本信息會(huì )展現在文檔頁(yè)面中)
           * 訪(fǎng)問(wèn)地址:http://項目實(shí)際地址/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類(lèi)")
      public class TestController {
          @ApiOperation(value="根據id查詢(xún)名字",notes = "備注:無(wú)")
          @ApiImplicitParam(name = "id",value = "用戶(hù)id",required = true,
                  paramType = "query",dataType = "Integer")
          @RequestMapping("/getNameById")
          @ResponseBody
          public String getNameById(int id){
              return "張三";
          }
      }

      4.啟動(dòng)測試:

      http://localhost:8080/swagger-ui.html

      四. 訪(fǎng)問(wèn)404Bug的解決方法

      Swagger UI 界面介紹:

      五. Model對象增刪改查演示

      對User類(lèi)實(shí)現增刪改查,生成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  
      有點(diǎn)BUG  就是list集合中的增刪改
       */
      @RestController
      @Api("User類(lèi)的增刪改查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);
          }
          /**
           * 根據id查User
           */
          @ApiOperation("根據id查用戶(hù)")
          @ApiImplicitParam(name = "id",value = "用戶(hù)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("查詢(xún)全部用戶(hù)")
          @RequestMapping(value="/user/get",method = RequestMethod.GET)
          public List<User> getAllUser(){
              System.out.println("getAllUser");
              return users;
          }
      
          /**
           * 添加User
           */
          @ApiOperation("添加用戶(hù)")
          @ApiImplicitParam(name="user",value = "用戶(hù)對象",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("根據id刪除用戶(hù)")
          @ApiImplicitParam(name = "id",value = "用戶(hù)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("根據id更新用戶(hù)")
          @ApiImplicitParams({
                  @ApiImplicitParam(name = "id",value = "用戶(hù)id",
                          required = true,paramType = "path",
                          dataType = "Integer"),
                  @ApiImplicitParam(name = "user",value = "用戶(hù)對象",
                          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. 查詢(xún)全部:


      2. 根據id查:


      3. 添加用戶(hù):



      4.更新用戶(hù):


      5. 刪除用戶(hù):

      到此這篇關(guān)于在SpringBoot項目中的使用Swagger的方法示例的文章就介紹到這了,更多相關(guān)SpringBoot使用Swagger內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

      免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。

      JAPANESE无码中文字幕| 亚洲熟妇无码另类久久久| 少妇中文字幕乱码亚洲影视| 日韩成AV人片在线观看| 大地资源网最新在线播放| 人妻激情乱人伦|