springboot集成swagger2

 1、swagger簡介

  Swagger是一款RESTful接口的文檔在線自動生成、功能測試功能框架。一個規範和完整的框架,用於生成、描述、調用和可視化RESTful風格的Web服務,加上swagger-ui,可以有很好的呈現。

  當我們在後臺的接口修改了後,swagger可以實現自動的更新,而不需要人爲的維護這個接口進行測試。

 

/'swægə/    v. 大搖大擺地走,趾高氣揚地行走或行事;嚇唬,虛張聲勢嚇人;吹牛

 

2:基於前面的知識點

  本知識點在springboot使用基於Mybatis註解方式實現的CRUD的基礎上進行的。

3、springboot與swagger的集成:
  第一步:jar包的引入:
        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.4.0</version>
        </dependency>
  第二步:swagger的配置啓動類編寫:
         要使用swagger要進行一些配置,這個在界面的圖上是可以顯示的:類似於說明書:在這個類中我們會使用註解來進行啓動 swagger:

  

具體配置如下:

package cn.xdf.springboot;
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;
//swagger2的配置文件,在項目的啓動類的同級文件建立
@Configuration
@EnableSwagger2
//是否開啓swagger,正式環境一般是需要關閉的(避免不必要的漏洞暴露!),可根據springboot的多環境配置進行設置
@ConditionalOnProperty(name = "swagger.enable",  havingValue = "true")
public class Swagger2 {
     // swagger2的配置文件,這裏可以配置swagger2的一些基本的內容,比如掃描的包等等
     @Bean
     public Docket createRestApi() {
          return new Docket(DocumentationType.SWAGGER_2)
                   .apiInfo(apiInfo())
                   .select()
                   // 爲當前包路徑
                   .apis(RequestHandlerSelectors.basePackage("cn.xdf.springboot.controller")).paths(PathSelectors.any())
                   .build();
     }
     // 構建 api文檔的詳細信息函數,注意這裏的註解引用的是哪個
     private ApiInfo apiInfo() {
          return new ApiInfoBuilder()
                   // 頁面標題
                   .title("Spring Boot 測試使用 Swagger2 構建RESTful API")
                   // 創建人信息
                   .contact(new Contact("MrZhang",  "https://www.cnblogs.com/zs-notes/category/1258467.html",  "[email protected]"))
                   // 版本號
                   .version("1.0")
                   // 描述
                   .description("API 描述")
                   .build();
     }
}

  修改添加application.properties文件

#是否激活 swagger true or false
swagger.enable=true
  第三步:使用swagger來進行模擬測試:
         使用swagger2來進行測試接口主要是在哪些類中使用:這裏我們依然選擇在controller層:
package cn.xdf.springboot.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import  org.springframework.web.bind.annotation.RestController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.xdf.springboot.mapper.CategoryMapper;
import cn.xdf.springboot.pojo.Category;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
/**
* 控制層 簡單演示增刪改查及分頁
*
*/
@RestController
@RequestMapping("api")
@Api("swaggerDemoController相關的api")
public class SwaggerDemoController {

    @Autowired
    CategoryMapper categoryMapper;
    private static final Logger logger=  LoggerFactory.getLogger(SwaggerDemoController.class);
    //1.商品添加
    //@PutMapping("add") 添加方法--restful風格
    @PutMapping("add")
    @ApiOperation(value="商品新增")
    //正常業務時, 需要在category類裏或者server層進行事務控制,控制層一般不進行業務控制的。
    //@Transactional(rollbackFor = Exception.class)
    //@RequestParam 接收頁面中的請求的參數
    public Map<String,Object> addCategory(@RequestParam  String name){
      Category category = new Category();
      category.setName(name);
      categoryMapper.save(category);
      logger.info("開始新增某個商品信息");
        Map<String,Object> result = new  HashMap<String,Object>();
        result.put("respCode", "01");
        result.put("respMsg", "新增成功!");
        result.put("data", category);
        return result;
    }
    //2.商品修改
    //@PostMapping("update")  修改方法--restful風格
    @PostMapping("update")  
    @ApiOperation(value = "商品修改", notes = "修改數據庫中某個的商品信息")
    //@RequestBody 接收頁面中的請求的參數對象(適用於post請求)
    //當入參爲實體對象時,需要在方法上加@Valid或@Validated或者在參數前加@Valid或@Validated,或者在類上加@Validated
    public Map<String,Object> updateCategory(@Valid  @RequestBody  Category category) {
      Map<String,Object> result = new  HashMap<String,Object>();
      Category categoryGet =  categoryMapper.get(category.getId());
      if(categoryGet == null || "".equals(categoryGet)){
          try {
                   throw new Exception("修改的該商品不存在!");
              } catch (Exception e) {
                   e.printStackTrace();
              }
           result.put("respCode", "03");
           result.put("respMsg", "修改的該商品不存在!");
           result.put("data", category);
           return result;
      }
        categoryMapper.update(category);
        logger.info("開始修改某個商品信息");
        result.put("respCode", "03");
         result.put("respMsg", "修改成功!");
         result.put("data", category);
        return result;
    }
    //3.商品刪除
    //@DeleteMapping("/delete/{id}") 刪除方法--restful風格
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根據id刪除商品", notes = "商品刪除")
    @ApiImplicitParam(name = "id", value = "商品ID",  paramType = "path", required = true, dataType =  "Integer")
     public Map<String,Object>  deleteCategory(@PathVariable int id)throws Exception{   //@PathVariable 獲取/delete/{id}中id
      Category category = categoryMapper.get(id);
      Map<String,Object> result = new  HashMap<String,Object>();
      if (category == null) {
          try {
                   throw new Exception("用戶ID:" + id +  ",未找到");
              } catch (Exception e) {
                   e.printStackTrace();
              }
           result.put("respCode", "02");
           result.put("respMsg", "數據庫無該商品信息,刪除失敗!");
           result.put("data", category);
           return result;
          }else{
              categoryMapper.delete(id);
              logger.info("開始刪除某個商品信息");
              result.put("respCode", "01");
              result.put("respMsg", "刪除成功!");
              result.put("data", category);
              return result;  
          }
     }
    //4.根據ID查詢商品信息
    //@GetMapping("")  查詢方法--restful風格
    @GetMapping("/get/{id}")
    @ApiOperation(value = "根據id查詢商品", notes = "查詢數據庫中某個的商品信息")
    @ApiImplicitParam(name = "id", value = "商品ID",  paramType = "path", required = true, dataType =  "Integer")
    public Map<String,Object> getCategory(@PathVariable  int id) { //@PathVariable 獲取/get/{id}中id
      Category category = categoryMapper.get(id);
      logger.info("開始查詢某個商品信息");
      Map<String,Object> result = new  HashMap<String,Object>();
      if (category == null) {
          try {
                   throw new Exception("用戶ID:" + id +  ",未找到");
              } catch (Exception e) {
                   e.printStackTrace();
              }
           result.put("respCode", "02");
           result.put("respMsg", "數據庫無該商品信息");
           result.put("data", category);
           return result;
          }else{
             result.put("respCode", "01");
             result.put("respMsg", "查詢成功!");
             result.put("data", category);
             return result;
          }
    }
    //5.分頁查詢
    //@GetMapping("")  查詢方法--restful風格
    @GetMapping("/page")
    @ApiOperation(value="商品查詢(分頁)")        
    public Map<String,Object>  pageCategory(@RequestParam(value="start",defaultValue="0")int start,@RequestParam(value = "size", defaultValue =  "5") int size) throws Exception {
      //1. 在參數裏接受當前是第幾頁 start ,以及每頁顯示多少條數據  size。 默認值分別是0和5。
          //2. 根據start,size進行分頁,並且設置id 倒排序
          PageHelper.startPage(start,size,"id desc");
          //3. 因爲PageHelper的作用,這裏就會返回當前分頁的集合了
          List<Category> cs = categoryMapper.findAll();
          logger.info("開始分頁查詢商品信息");
          //4. 根據返回的集合,創建PageInfo對象
          PageInfo<Category> page = new PageInfo<>(cs);
          
        Map<String,Object> result = new  HashMap<String,Object>();
        result.put("respCode", "01");
        result.put("respMsg", "成功");
        result.put("data", page);
        return result;
    }
    
}

 

這樣swagger2與springboot就集成完畢了。
看下最終效果吧:
調試:點擊需要訪問的api列表,點擊try it out!按鈕,表示 執行。

----------------------------------------------------------------------------------------------------------------------------------------------------------------

而且這些方法是實時更新的!!!
 
接下來測試一個新增方法:

 

 查詢方法:

 

另外,大家可下載示例,查看自定義的字符出現的位置,這樣可以對其有個大致瞭解,各字段的作用領域是哪裏
 
Swagger常用屬性說明:

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章