Spring boot集成Swagger,并配置多個(gè)掃描路徑

Spring boot集成Swagger,并配置多個(gè)掃描路徑

1:認(rèn)識(shí)Swagger

Swagger 是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)。總體目標(biāo)是使客戶端和文件系統(tǒng)作為服務(wù)器以同樣的速度來更新。文件的方法,參數(shù)和模型緊密集成到服務(wù)器端的代碼,允許API來始終保持同步。

作用:

? 1. 接口的文檔在線自動(dòng)生成。

? 2. 功能測(cè)試。

Swagger是一組開源項(xiàng)目,其中主要要項(xiàng)目如下:

  1. Swagger-tools:提供各種與Swagger進(jìn)行集成和交互的工具。例如模式檢驗(yàn)、Swagger 1.2文檔轉(zhuǎn)換成Swagger 2.0文檔等功能。

  2. Swagger-core: 用于Java/Scala的的Swagger實(shí)現(xiàn)。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進(jìn)行集成。

  3. Swagger-js: 用于JavaScript的Swagger實(shí)現(xiàn)。

  4. Swagger-node-express: Swagger模塊,用于node.js的Express web應(yīng)用框架。

  5. Swagger-ui:一個(gè)無依賴的HTML、JS和CSS集合,可以為Swagger兼容API動(dòng)態(tài)生成優(yōu)雅文檔。

  6. Swagger-codegen:一個(gè)模板驅(qū)動(dòng)引擎,通過分析用戶Swagger資源聲明以各種語言生成客戶端代碼。

2:spring boot 集成 swagger

2.1 引入POM

 <!-- swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>

2.2 配置swagger

在Application.java同級(jí)或子包中創(chuàng)建SwaggerConfig.java

package com.example.demo.swagger;

import org.springframework.context.annotation.Bean;
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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 創(chuàng)建API應(yīng)用
     * apiInfo() 增加API相關(guān)信息
     * 通過select()函數(shù)返回一個(gè)ApiSelectorBuilder實(shí)例,用來控制哪些接口暴露給Swagger來展現(xiàn),
     * 本例采用指定掃描的包路徑來定義指定要建立API的目錄。
     *
     * @return
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 創(chuàng)建該API的基本信息(這些基本信息會(huì)展現(xiàn)在文檔頁面中)
     * 訪問地址:http://項(xiàng)目實(shí)際地址/swagger-ui.html
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("測(cè)試 APIs")
                .description("測(cè)試api接口文檔")
                .termsOfServiceUrl("http://www.baidu.com")
                .version("1.0")
                .build();
    }
}

2.3 添加文檔內(nèi)容

在完成了上述配置后,其實(shí)已經(jīng)可以生產(chǎn)文檔內(nèi)容,我們?cè)L問http://localhost:8080/swagger-ui.html。如圖

1539140458684.png

但是這樣的文檔主要針對(duì)請(qǐng)求本身,描述的主要來源是函數(shù)的命名,對(duì)用戶并不友好,我們通常需要自己增加一些說明來豐富文檔內(nèi)容。

Swagger使用的注解及其說明:

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

@ApiOperation:注解來給API增加方法說明。

@ApiImplicitParams : 用在方法上包含一組參數(shù)說明。

@ApiImplicitParam:用來注解來給方法入?yún)⒃黾诱f明。

@ApiResponses:用于表示一組響應(yīng)

@ApiResponse:用在@ApiResponses中,一般用于表達(dá)一個(gè)錯(cuò)誤的響應(yīng)信息

? l code:數(shù)字,例如400

? l message:信息,例如"請(qǐng)求參數(shù)沒填好"

? l response:拋出異常的類

@ApiModel:描述一個(gè)Model的信息(一般用在請(qǐng)求參數(shù)無法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)

? l @ApiModelProperty:描述一個(gè)model的屬性

例如:

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
@Api(tags="用戶系統(tǒng)-用戶管理")
public class UserController {


    @Autowired
    private UserService userService;


    @GetMapping("updateMoblie")
    @ApiOperation(value="更新手機(jī)號(hào)", notes = "更新手機(jī)號(hào)接口")
    public String updateMoblie(Long userId){
        userService.updateMobile(userId);
        return "success";
    }

}

結(jié)果如圖


1539140725037.png

以上我們完成了spring boot與swagger的集成,但是使用springfox中的 RequestHandlerSelectors.basePackage("com.xxx") 只能支持單個(gè)包路徑的掃描匹配,如果我們業(yè)務(wù)中分了多個(gè)包,swagger怎么能掃描到呢?

3: swagger 多包掃描配置

要解決這個(gè)問題,我們可以參考一下RequestHandlerSelectors.basePackage的源碼

public class RequestHandlerSelectors {
  private RequestHandlerSelectors() {
    throw new UnsupportedOperationException();
  }

  /**
   * Any RequestHandler satisfies this condition
   *
   * @return predicate that is always true
   */
  public static Predicate<RequestHandler> any() {
    return Predicates.alwaysTrue();
  }

  /**
   * No RequestHandler satisfies this condition
   *
   * @return predicate that is always false
   */
  public static Predicate<RequestHandler> none() {
    return Predicates.alwaysFalse();
  }

  /**
   * Predicate that matches RequestHandler with handlers methods annotated with given annotation
   *
   * @param annotation - annotation to check
   * @return this
   */
  public static Predicate<RequestHandler> withMethodAnnotation(final Class<? extends Annotation> annotation) {
    return new Predicate<RequestHandler>() {
      @Override
      public boolean apply(RequestHandler input) {
        return input.isAnnotatedWith(annotation);
      }
    };
  }

  /**
   * Predicate that matches RequestHandler with given annotation on the declaring class of the handler method
   *
   * @param annotation - annotation to check
   * @return this
   */
  public static Predicate<RequestHandler> withClassAnnotation(final Class<? extends Annotation> annotation) {
    return new Predicate<RequestHandler>() {
      @Override
      public boolean apply(RequestHandler input) {
        return declaringClass(input).transform(annotationPresent(annotation)).or(false);
      }
    };
  }

  private static Function<Class<?>, Boolean> annotationPresent(final Class<? extends Annotation> annotation) {
    return new Function<Class<?>, Boolean>() {
      @Override
      public Boolean apply(Class<?> input) {
        return input.isAnnotationPresent(annotation);
      }
    };
  }


  private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
    return new Function<Class<?>, Boolean>() {
      @Override
      public Boolean apply(Class<?> input) {
        return ClassUtils.getPackageName(input).startsWith(basePackage);
      }
    };
  }

  /**
   * Predicate 匹配RequestHandler,并為處理程序方法的類提供基本包名.
   * predicate 包括與所提供的basePackage匹配的所有請(qǐng)求處理程序
   *
   * @param basePackage - base package of the classes
   * @return this
   */
  public static Predicate<RequestHandler> basePackage(final String basePackage) {
    return new Predicate<RequestHandler>() {
      @Override
      public boolean apply(RequestHandler input) {
        return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
      }
    };
  }

  private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
    return Optional.fromNullable(input.declaringClass());
  }

}

我們看到 swagger 是通過Predicate 的apply 方法的返回值來判斷是非匹配的 我們可以通過改造basePackage方法來實(shí)現(xiàn)多包掃描,改造 SwaggerConfig 如下

package com.example.demo.swagger;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {


    // 定義分隔符
    private static final String splitor = ";";

    /**
     * 創(chuàng)建API應(yīng)用
     * api() 增加API相關(guān)信息
     * 通過select()函數(shù)返回一個(gè)ApiSelectorBuilder實(shí)例,用來控制哪些接口暴露給Swagger來展現(xiàn),
     * 本例采用指定掃描的包路徑來定義指定要建立API的目錄。
     *
     * @return
     */
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
 .apis(basePackage("com.example.demo.controller"+splitor+"com.example.demo.test"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 構(gòu)建 api文檔的詳細(xì)信息函數(shù)
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("測(cè)試 APIs")
                .description("測(cè)試api接口文檔")
                .version("1.0")
                .build();
    }


    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage)     {
        return input -> {
            // 循環(huán)判斷匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }


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

通過以上配置 我們就可以掃描到 com.example.demo.controller 和 com.example.demo.test 兩個(gè)包下的接口信息了。

完!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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