Spring boot整合Swagger
Spring boot整合Swagger,並配置多個掃描路徑
1:認識Swagger
Swagger 是一個規範和完整的框架,用於生成、描述、呼叫和視覺化 RESTful 風格的 Web 服務。總體目標是使客戶端和檔案系統作為伺服器以同樣的速度來更新。檔案的方法,引數和模型緊密整合到伺服器端的程式碼,允許API來始終保持同步。
作用:
1. 介面的文件線上自動生成。
2. 功能測試。
Swagger是一組開源專案,其中主要要專案如下:
-
Swagger-tools:提供各種與Swagger進行整合和互動的工具。例如模式檢驗、Swagger 1.2文件轉換成Swagger 2.0文件等功能。
-
Swagger-core: 用於Java/Scala的的Swagger實現。與JAX-RS(Jersey、Resteasy、CXF...)、Servlets和Play框架進行整合。
-
Swagger-js: 用於JavaScript的Swagger實現。
-
Swagger-node-express: Swagger模組,用於node.js的Express web應用框架。
-
Swagger-ui:一個無依賴的HTML、JS和CSS集合,可以為Swagger相容API動態生成優雅文件。
-
Swagger-codegen:一個模板驅動引擎,通過分析使用者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同級或子包中建立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 { /** * 建立API應用 * apiInfo() 增加API相關資訊 * 通過select()函式返回一個ApiSelectorBuilder例項,用來控制哪些介面暴露給Swagger來展現, * 本例採用指定掃描的包路徑來定義指定要建立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(); } /** * 建立該API的基本資訊(這些基本資訊會展現在文件頁面中) * 訪問地址:http://專案實際地址/swagger-ui.html * * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("測試 APIs") .description("測試api介面文件") .termsOfServiceUrl("http://www.baidu.com") .version("1.0") .build(); } }
2.3 新增文件內容
在完成了上述配置後,其實已經可以生產文件內容,我們訪問http://localhost:8080/swagger-ui.html。如圖
但是這樣的文件主要針對請求本身,描述的主要來源是函式的命名,對使用者並不友好,我們通常需要自己增加一些說明來豐富文件內容。
Swagger使用的註解及其說明:
@Api:用在類上,說明該類的作用。 @ApiOperation:註解來給API增加方法說明。 @ApiImplicitParams : 用在方法上包含一組引數說明。 @ApiImplicitParam:用來註解來給方法入參增加說明。 @ApiResponses:用於表示一組響應 @ApiResponse:用在@ApiResponses中,一般用於表達一個錯誤的響應資訊 l.code:數字,例如400 l.message:資訊,例如"請求引數沒填好" l response:丟擲異常的類 @ApiModel:描述一個Model的資訊(一般用在請求引數無法使用@ApiImplicitParam註解進行描述的時候) l @ApiModelProperty:描述一個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="使用者系統-使用者管理") public class UserController { @Autowired private UserService userService; @GetMapping("updateMoblie") @ApiOperation(value="更新手機號", notes = "更新手機號介面") public String updateMoblie(Long userId){ userService.updateMobile(userId); return "success"; } }
結果如圖:
以上我們完成了spring boot與swagger的整合,但是使用springfox中的 RequestHandlerSelectors.basePackage("com.xxx") 只能支援單個包路徑的掃描匹配,如果我們業務中分了多個包,swagger怎麼能掃描到呢?
3: swagger 多包掃描配置
要解決這個問題,我們可以參考一下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匹配的所有請求處理程式 * * @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方法來實現多包掃描,改造 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 = ";"; /** * 建立API應用 * api() 增加API相關資訊 * 通過select()函式返回一個ApiSelectorBuilder例項,用來控制哪些介面暴露給Swagger來展現, * 本例採用指定掃描的包路徑來定義指定要建立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(); } /** * 構建 api文件的詳細資訊函式 * * @return */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("測試 APIs") .description("測試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 -> { // 迴圈判斷匹配 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 兩個包下的介面資訊了。