swagger基本使用指南


  1. Maven依賴

    <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>
    
  2. SpringBoot配置

    1. 新建Swagger2.java類,請確保放在能被SpringBoot掃描到的位置
    @Configuration
    @EnableSwagger2
    public class Swagger2 {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2).apiInfo(this.apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("controller包"))
                .paths(PathSelectors.any())
                .build();
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder().title("springboot利用swagger構建api文檔")
                .description("項目描述,代碼地址 https://github.com/ljinlin41")
                .termsOfServiceUrl("https://github.com/ljinlin41")
                .version("1.0")
                .build();
        }
    
    }
    
  3. API Web地址

    1. 此時啟動SpringBoot項目,瀏覽http://localhost:8080/swagger-ui.html,可以發現已經有了項目的API信息。但這些信息是swagger自動配置的,如果需要定制更詳細的信息,可以使用注解。
  4. 使用注解

    1. @Api
      1. 功能:描述controller類
      2. 注解位置:類
      3. 常用注解屬性
        1. tags = "" // 描述此controller類
    2. @ApiOperation
      1. 功能:描述一個方法或者一個API接口
      2. 注解位置:方法
      3. 常用注解屬性
        1. value = "" // 描述方法
        2. notes = "" // 描述方法詳細信息
    3. @ApiImplicitParam
      1. 功能:描述方法或接口參數
      2. 注解位置: 方法
      3. 注解屬性
        1. name = "" // 方法或接口的形參, 注意要與方法的參數名稱相同
        2. value = "" // 對參數的描述
        3. paramType = "" // 參數傳遞方式,此屬性的可選值 ["header", "query", "path", "body", "form"]
          1. header,使用@RequestHeader獲取的參數
          2. query,使用@RequestParam獲取的參數,常用於GET請求
          3. path,使用@PathVariable獲取的參數
          4. body,使用@RequestBody獲取的參數,常用於POST請求,對象參數
        4. dataType = "" // 參數類型,例如 string, int, ArrayList, POJO類
    4. @ApiImplicitParams
      1. 功能:匯集多個參數
      2. 注解位置: 方法
      3. 注解屬性
        1. @ApiImplicitParam組成的列表
  5. 項目代碼地址
    https://github.com/ljinlin41/demo-swagger


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM