Springboot2x集成Swagger2

Springboot2x集成Swagger2

一、環(huán)境

  1. jdk 1.8
  2. Swagger 2.9.2
  3. Swagger-ui 2.9.2
  4. Spring Boot 2.1.9

二、代碼示例

//導(dǎo)入依賴:
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
    <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger2</artifactId>
          <version>2.9.2</version>
      </dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
      <dependency>
          <groupId>io.springfox</groupId>
          <artifactId>springfox-swagger-ui</artifactId>
          <version>2.9.2</version>
        </dependency>

//添加如下配置類:

@Configuration
@EnableSwagger2
@EnableAutoConfiguration
public class Swagger2Config {

    /**
     *
     * @return
     */
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //此處根據(jù)情況自行添加需要將哪些接口納入Swagger 文檔管理。此處應(yīng)用basePackage管理,還可以利用注解管理
                //如果填寫錯誤的話會出現(xiàn)“No operations defined in spec!” 的問題。
                .apis(RequestHandlerSelectors.basePackage("com.iammn.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     *
     * @return
     */
    private ApiInfo apiInfo(){
        Contact contact = new Contact("Swagger2 demo", "http://localhost", "郵箱");
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2構(gòu)建RESTFUL API")
                .description("描述信息")
                .termsOfServiceUrl("http://localhost")
                .version("1.0")
                .contact(contact)
                .build();
    }
}

//示例controller 類:

@RestController
@Api(value = "測試 swagger2")
public class Swagger2TestController {

    /**
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/swagger", method = RequestMethod.GET)
    @ApiOperation(value = "返回用戶輸入的參數(shù)內(nèi)容", notes = "notes")
    @ApiImplicitParam(paramType = "query", name = "param", value = "值",required = true, dataType = "string")
    public String swagger(String param){
        return param;
    }
}

然后直接訪問:http://localhost:8080/swagger-ui.html (端口和ip根據(jù)自己的配置來)

三、Swagger常用注解:

swagger通過注解表明該接口會生成文檔,包括接口名、請求方法、參數(shù)、返回信息的等等。
@Api:修飾整個類,描述Controller的作用
@ApiOperation:描述一個類的一個方法,或者說一個接口
@ApiParam:單個參數(shù)描述
@ApiModel:用對象來接收參數(shù)
@ApiProperty:用對象接收參數(shù)時,描述對象的一個字段
@ApiResponse:HTTP響應(yīng)其中1個描述
@ApiResponses:HTTP響應(yīng)整體描述
@ApiIgnore:使用該注解忽略這個API
@ApiError :發(fā)生錯誤返回的信息
@ApiImplicitParam:一個請求參數(shù)
@ApiImplicitParams:多個請求參數(shù)

四、常見錯誤

  1. 項(xiàng)目啟動起來了,發(fā)現(xiàn)訪問http://localhost:8080/swagger-ui.html 的時候,出現(xiàn)了404。最后找到原因是Swager-ui的依賴沒有導(dǎo)入進(jìn)來。沒有提示報錯,如果出現(xiàn)此情況,需要自己去核對依賴是否正確引入!
  2. 如果配置類中添加了注解 @EnableWebMvc。為了避免覆蓋了,Spring Boot resources 下的靜態(tài)資源。采用如下代碼:
@Configuration
@EnableSwagger2
@EnableAutoConfiguration
@EnableWebMvc
public class Swagger2Config extends WebMvcConfigurationSupport {

  /**
   *
   * @return
   */
  @Bean
  public Docket createRestApi(){
      return new Docket(DocumentationType.SWAGGER_2)
              .apiInfo(apiInfo())
              .select()
              .apis(RequestHandlerSelectors.basePackage("com.iammn.controller"))
              .paths(PathSelectors.any())
              .build();
  }

  /**
   *
   * @return
   */
  private ApiInfo apiInfo(){
      Contact contact = new Contact("Swagger2 demo", "http://localhost", "郵箱");
      return new ApiInfoBuilder()
              .title("Spring Boot中使用Swagger2構(gòu)建RESTFUL API")
              .description("描述信息")
              .termsOfServiceUrl("http://localhost")
              .version("1.0")
              .contact(contact)
              .build();
  }

  /**
   * 防止@EnableMvc把默認(rèn)的靜態(tài)資源路徑覆蓋了,手動設(shè)置的方式
   *
   * @param registry
   */
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
      // 解決靜態(tài)資源無法訪問
      registry.addResourceHandler("/**")
              .addResourceLocations("classpath:/static/");
      // 解決swagger無法訪問
      registry.addResourceHandler("/swagger-ui.html")
              .addResourceLocations("classpath:/META-INF/resources/");
      // 解決swagger的js文件無法訪問
      registry.addResourceHandler("/webjars/**")
              .addResourceLocations("classpath:/META-INF/resources/webjars/");
  }
}

5、環(huán)境配置:

如果說我需要在dev環(huán)境開啟swagger2的調(diào)試,而在生產(chǎn)環(huán)境關(guān)閉swagger2的調(diào)試,可以使用如下配置:

swagger:
  enable: true

六、參考文檔:

  1. https://blog.csdn.net/sanyaoxu_2/article/details/80555328
  2. 官網(wǎng):http://swagger.io
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 今天技術(shù)總監(jiān)說:小明,我們本次3.0改造,使用swagger2.0作為前后端分離的接口規(guī)范,它可以一鍵生成前后端的...
    coder小明閱讀 3,465評論 4 12
  • spring security是spring家族的一個安全框架,入門簡單。對比shiro,它自帶登錄頁面,自動完成...
    b47251f96536閱讀 450評論 0 1
  • NumPy - Ndarray 對象 NumPy 中定義的最重要的對象是稱為 ndarray 的 N 維數(shù)組類型。...
    數(shù)據(jù)小黑升值記閱讀 168評論 0 0
  • 圖片加載框架Picasso源碼的簡單分析(一) 本篇文章只是對Picasso加載流程做加單的分析,相對于其他常用的...
    愛踢球的程序員閱讀 784評論 0 50
  • 還有一周時間才能放五一假,家人和朋友們急不可耐地規(guī)劃著四天時間。我想回娘家住兩天,陪陪爸媽。 今天晚上兒子說他想出...
    李瑞居閱讀 219評論 0 1

友情鏈接更多精彩內(nèi)容