1. 程式人生 > 實用技巧 >《HDU 2020 多校 第一場》

《HDU 2020 多校 第一場》

Swagger使用

1、描述

Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。

作用:

1.介面的文件線上自動生成。

2.功能測試。

2、運用

a) maven匯入Swagger

<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>

b) 建立Swagger2配置類

@Configuration
@EnableSwagger2
public class Swagger {
​
   @Bean
   public Docket docket(){
       return new Docket(DocumentationType.SWAGGER_2)
         .apiInfo(apiInfo())
         .select()
         .apis(RequestHandlerSelectors.basePackage("com.example.springbootjpa.jpademo.controller"))
         .paths(PathSelectors.any())
         .build();
   }
​
   
public ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("利用swagger2構建的API文件") .description("用restful風格寫介面") .termsOfServiceUrl("") .version("1.0") .build(); } }

如上所示,docket() 方法建立Docket的Bean物件,apiInfo()則是建立ApiInfo的基本資訊.

3、註解及其說明

@Api : 用在類上,說明該類的主要作用。

@ApiOperation:用在方法上,給API增加方法說明。

@ApiImplicitParams : 用在方法上,包含一組引數說明。

@ApiImplicitParam:用來註解來給方法入參增加說明。

@ApiResponses:用於表示一組響應。

@ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應資訊

​ l code:數字,例如400

​ l message:資訊,例如"請求引數沒填好"

​ l response:丟擲異常的類

@ApiModel:用在返回物件類上,描述一個Model的資訊(一般用在請求引數無法使用@ApiImplicitParam註解進行描述的時候)

​ l @ApiModelProperty:描述一個model的屬性

以下僅僅是一個例子,其實我個人在開發中很少使用@ApiImplicitParam 作為引數的描述,這樣描述在引數過多的條件下會有點麻煩。個人一般是將引數封裝為一個完整物件(特別是GET方法),並利用@ApiModel註解去定義引數,如果不需要作為查詢條件的,則加一個hidden = true,如果是必填屬性,則增加一個required = true即可。

例子:

@RestController
@RequestMapping("emp")
@Api(value = "使用者管理類")
public class EmployeeController {
​
 @Autowired
 private EmployeeReposiroty employeeReposiroty;
​
      /**
      * 增加人物
      * @param employee
      * @return
      */
     @PostMapping(value = "employee")
     @ApiOperation(value = "新增一個使用者",notes = "新增之後返回物件")
     @ApiImplicitParam(paramType = "query",name = "employee",value = "使用者",required = true)
     @ApiResponse(code = 400,message = "引數沒有填好",response = String.class)
     public String insert(Employee employee){
         Employee employee1 = employeeReposiroty.save(employee);
         if(employee1 != null) {
             return SysNode.Judge.SUCCESS.getResult();
         }else {
             return SysNode.Judge.FAILD.getResult();
         }
     }
​
      /**
      * 刪除單個使用者
      * @param id
      * @return
      */
      @DeleteMapping(value = "employee/{id}")
      @ApiOperation(value = "刪除使用者",notes = "根據成員id刪除單個使用者")
      @ApiImplicitParam(paramType = "path",name = "id",value = "使用者id",required = true,dataType = "Integer")
      @ApiResponse(code = 400,message = "引數沒有填好",response = String.class)
      public String delete(@PathVariable("id")Integer id){
           try{
                employeeReposiroty.deleteById(id);
                return SysNode.Judge.SUCCESS.getResult();
           }catch (Exception e){
                e.printStackTrace();
               return SysNode.Judge.FAILD.getResult();
           }
      }
​
      /**
      * 修改單個成員
      * @param employee
      * @return
      */
      @PutMapping(value = "employee/{id}")
      @ApiOperation(value = "修改使用者資訊",notes = "根據成員id修改單個使用者")
      public String update(Employee employee){
           /**
           * save方法如果引數屬性缺失,會導致原本存在的資料為null
           */
           Employee employee1 = employeeReposiroty.saveAndFlush(employee);
           if (employee1 != null) {
                return SysNode.Judge.SUCCESS.getResult();
           }else {
               return SysNode.Judge.FAILD.getResult();
           }
      }
​
      /**
      * 獲取所有成員,升序排列
      * @return
      */
      @GetMapping(value = "employee/sort")
      @ApiOperation(value = "查詢全部使用者",notes = "預設根據升序查詢全部使用者資訊")
      public List<Employee> findAll(){
           Sort orders = new Sort(Sort.Direction.DESC,"employeeId");
           List<Employee> employeeList = employeeReposiroty.findAll(orders);
           return employeeList;
      }
​
      /**
     * 獲取所有成員,升序排列
     * @return
      */
      @GetMapping(value = "employee/pageSort")
      @ApiOperation(value = "查詢使用者資訊",notes = "查詢使用者資訊")
      @ApiImplicitParams({
           @ApiImplicitParam(paramType = "query",name = "sort",value = "排序方式:asc|desc",dataType = "String",required = true),
           @ApiImplicitParam(paramType = "query",name = "pagenumber",value = "第幾頁",dataType = "Integer",required = true),
           @ApiImplicitParam(paramType = "query",name = "pageSize",value = "分頁數",dataType = "Integer",required = true)
      })
      public List<Employee> findAllByPage(String sort,Integer pagenumber,Integer pageSize){
           try {
                Sort.Direction sortlast;
                if("desc".equals(sort.toLowerCase())){
                     sortlast = Sort.Direction.DESC;
               }else{          
                      sortlast = Sort.Direction.ASC;
               }
                     Sort orders = new Sort(sortlast, "employeeId");
                     Pageable pageable = new PageRequest(pagenumber, pageSize, orders);
​
                     Page<Employee> employeePage = employeeReposiroty.findAll(pageable);
                     List<Employee> employeeList = employeePage.getContent();
                     return employeeList;
           }catch (Exception e){
                e.printStackTrace();
                return null;
           }
      }
    /**
     * 自定義拓展jpa,根據使用者名稱查詢單個使用者
     * @param username
     * @return
     */
     @GetMapping(value = "employee/find/{username}")
     @ApiOperation(value = "查詢使用者資訊",notes = "根據使用者登入名查詢該使用者資訊")
     @ApiImplicitParam(paramType = "path",name = "username",value = "使用者登入名",required = true,dataType = "String")
     public Employee findByUsername(@PathVariable("username") String username){
         List<Employee> employeeList = employeeReposiroty.findByUserNameOrderByEmployeeIdAsc(username);
         if (employeeList != null && !employeeList.isEmpty()){
             return employeeList.get(0);
         }
         return null;
     }
​
     /**
     * 測試用
     * @return
     */
     @GetMapping(value = "employee/grade")
     public List<Object[]> findEmployeeAndGrade(){
         Pageable pageable = new PageRequest(0,3);
​
         Page<Object[]> page = employeeReposiroty.findEmployeeAndGrade(pageable);
         System.out.println(page.getTotalElements()+"----------結果總數------------");
         System.out.println(page.getTotalPages()+"--------根據pageSize的總頁數-----------");
         System.out.println(page.getNumber()+"--------當前頁數,pageNumber----------");
         System.out.println(page.getNumberOfElements()+"--------當前頁有幾個資料--------");
         System.out.println(page.getSize()+"---------PageSize-------------");
         System.out.println(page.getSort()+"---------排序方式,沒有則是'UNSORTED'----------");
​
         List<Object[]> objects = page.getContent();
         return objects;
    }
}

4、測試登入 localhost:8080/swagger-ui.html

API 操作測試,修改

5、@ApiModel 接收物件傳參

注意: 在後臺採用物件接收引數時,Swagger自帶的工具採用的是JSON傳參, 測試時需要在引數上加入@RequestBody,正常執行採用form或URL提交時候請刪除。

例子:

@Data
@ApiModel(value = "使用者物件模型")
public class Employee {
​
   private Integer employeeId;
​
   @ApiModelProperty(value = "userName",required = true)
   private String userName;
​
   @ApiModelProperty(value = "age",required = true)
   private Integer age;
​
   @ApiModelProperty(value = "graId",required = true)
   private Integer graId;
​
   public interface Audit{};
​
   public interface Children{};
​
}