Swagger 3.0 天天刷屏,真的香嗎?


持續原創輸出,點擊上方藍字關注我

目錄

  • 前言
  • 官方文檔如何說?
  • Spring Boot版本說明
  • 添加依賴
  • springfox-boot-starter做了什么?
  • 擼起袖子就是干?
    • 定制一個基本的文檔示例
    • 文檔如何分組?
    • 如何添加授權信息?
    • 如何攜帶公共的請求參數?
  • 粗略是一個BUG
  • 總結

前言

最近頻繁被Swagger 3.0刷屏,官方表示這是一個突破性的變更,有很多的亮點,我還真不太相信,今天來帶大家嘗嘗鮮,看看這碗湯到底鮮不鮮....

官方文檔如何說?

該項目開源在Github上,地址:https://github.com/springfox/springfox

Swagger 3.0有何改動?官方文檔總結如下幾點:

  1. 刪除了對 springfox-swagger2的依賴
  2. 刪除所有 @EnableSwagger2...注解
  3. 添加了 springfox-boot-starter依賴項
  4. 移除了 guava等第三方依賴
  5. 文檔訪問地址改變了,改成了 http://ip:port/project/swagger-ui/index.html

姑且看到這里,各位初始感覺如何?

既然人家更新出來了,咱不能不捧場,下面就介紹下Spring Boot如何整合Swagger 3.0吧。

Spring Boot版本說明

作者使用Spring Boot的版本是2.3.5.RELEASE

添加依賴

Swagger 3.0已經有了與Spring Boot整合的啟動器,只需要添加以下依賴:

  <dependency>
 <groupId>io.springfox</groupId>  <artifactId>springfox-boot-starter</artifactId>  <version>3.0.0</version>  </dependency> 

springfox-boot-starter做了什么?

Swagger 3.0主推的一大特色就是這個啟動器,那么這個啟動器做了什么呢?

記住:啟動器的一切邏輯都在自動配置類中。

找到springfox-boot-starter的自動配置類,在/META-INF/spring.factories文件中,如下:

從上圖可以知道,自動配置類就是OpenApiAutoConfiguration,源碼如下:

@Configuration
@EnableConfigurationProperties(SpringfoxConfigurationProperties.class) @ConditionalOnProperty(value = "springfox.documentation.enabled", havingValue = "true", matchIfMissing = true) @Import({  OpenApiDocumentationConfiguration.class,  SpringDataRestConfiguration.class,  BeanValidatorPluginsConfiguration.class,  Swagger2DocumentationConfiguration.class,  SwaggerUiWebFluxConfiguration.class,  SwaggerUiWebMvcConfiguration.class }) @AutoConfigureAfter({ WebMvcAutoConfiguration.class, JacksonAutoConfiguration.class,  HttpMessageConvertersAutoConfiguration.class, RepositoryRestMvcAutoConfiguration.class }) public class OpenApiAutoConfiguration {  } 

敢情這個自動配置類啥也沒干,就光導入了幾個配置類(@Import)以及開啟了屬性配置(@EnableConfigurationProperties)。

3
3

重點:記住OpenApiDocumentationConfiguration這個配置類,初步看來這是個BUG,本人也不想深入,里面的代碼寫的實在拙劣,注釋都不寫。

擼起袖子就是干?

說真的,還是和以前一樣,真的沒什么太大的改變,按照文檔的步驟一步步來。

定制一個基本的文檔示例

一切的東西還是需要配置類手動配置,說真的,我以為會在全局配置文件中自己配置就行了。哎,想多了。配置類如下:

@EnableOpenApi
@Configuration @EnableConfigurationProperties(value = {SwaggerProperties.class}) public class SwaggerConfig {  /**  * 配置屬性  */  @Autowired  private SwaggerProperties properties;   @Bean  public Docket frontApi() {  return new Docket(DocumentationType.OAS_30)  //是否開啟,根據環境配置  .enable(properties.getFront().getEnable())  .groupName(properties.getFront().getGroupName())  .apiInfo(frontApiInfo())  .select()  //指定掃描的包  .apis(RequestHandlerSelectors.basePackage(properties.getFront().getBasePackage()))  .paths(PathSelectors.any())  .build();  }   /**  * 前台API信息  */  private ApiInfo frontApiInfo() {  return new ApiInfoBuilder()  .title(properties.getFront().getTitle())  .description(properties.getFront().getDescription())  .version(properties.getFront().getVersion())  .contact( //添加開發者的一些信息  new Contact(properties.getFront().getContactName(), properties.getFront().getContactUrl(),  properties.getFront().getContactEmail()))  .build();  } } 

@EnableOpenApi這個注解文檔解釋如下:

Indicates that Swagger support should be enabled.
This should be applied to a Spring java config and should have an accompanying '@Configuration' annotation.
Loads all required beans defined in @see SpringSwaggerConfig

什么意思呢?大致意思就是只有在配置類標注了@EnableOpenApi這個注解才會生成Swagger文檔

@EnableConfigurationProperties這個注解使開啟自定義的屬性配置,這是作者自定義的Swagger配置。

總之還是和之前一樣配置,根據官方文檔要求,需要在配置類上加一個@EnableOpenApi注解。

文檔如何分組?

我們都知道,一個項目可能分為前台后台APP端小程序端.....每個端的接口可能還相同,不可能全部放在一起吧,肯定是要區分開的。

因此,實際開發中文檔肯定是要分組的。

分組其實很簡單,SwaggerIOC中注入一個Docket即為一個組的文檔,其中有個groupName()方法指定分組的名稱。

因此只需要注入多個Docket指定不同的組名即可,當然,這些文檔的標題、描述、掃描的路徑都是可以不同定制的。

如下配置兩個Docket,分為前台和后台,配置類如下:

@EnableOpenApi
@Configuration @EnableConfigurationProperties(value = {SwaggerProperties.class}) public class SwaggerConfig {  /**  * 配置屬性  */  @Autowired  private SwaggerProperties properties;   @Bean  public Docket frontApi() {  return new Docket(DocumentationType.OAS_30)  //是否開啟,根據環境配置  .enable(properties.getFront().getEnable())  .groupName(properties.getFront().getGroupName())  .apiInfo(frontApiInfo())  .select()  //指定掃描的包  .apis(RequestHandlerSelectors.basePackage(properties.getFront().getBasePackage()))  .paths(PathSelectors.any())  .build();  }   /**  * 前台API信息  */  private ApiInfo frontApiInfo() {  return new ApiInfoBuilder()  .title(properties.getFront().getTitle())  .description(properties.getFront().getDescription())  .version(properties.getFront().getVersion())  .contact( //添加開發者的一些信息  new Contact(properties.getFront().getContactName(), properties.getFront().getContactUrl(),  properties.getFront().getContactEmail()))  .build();  }   /**  * 后台API  */  @Bean  public Docket backApi() {  return new Docket(DocumentationType.OAS_30)  //是否開啟,根據環境配置  .enable(properties.getBack().getEnable())  .groupName("后台管理")  .apiInfo(backApiInfo())  .select()  .apis(RequestHandlerSelectors.basePackage(properties.getBack().getBasePackage()))  .paths(PathSelectors.any())  .build();  }   /**  * 后台API信息  */  private ApiInfo backApiInfo() {  return new ApiInfoBuilder()  .title(properties.getBack().getTitle())  .description(properties.getBack().getDescription())  .version(properties.getBack().getVersion())  .contact( //添加開發者的一些信息  new Contact(properties.getBack().getContactName(), properties.getBack().getContactUrl(),  properties.getBack().getContactEmail()))  .build();  }  } 

屬性配置文件SwaggerProperties如下,分為前台和后台兩個不同屬性的配置:

/**  * swagger的屬性配置類  */ @ConfigurationProperties(prefix = "spring.swagger") @Data public class SwaggerProperties {   /**  * 前台接口配置  */  private SwaggerEntity front;   /**  * 后台接口配置  */  private SwaggerEntity back;   @Data  public static class SwaggerEntity {  private String groupName;  private String basePackage;  private String title;  private String description;  private String contactName;  private String contactEmail;  private String contactUrl;  private String version;  private Boolean enable;  } } 

此時的文檔截圖如下,可以看到有了兩個不同的分組:

如何添加授權信息?

現在項目API肯定都需要權限認證,否則不能訪問,比如請求攜帶一個TOKEN

在Swagger中也是可以配置認證信息,這樣在每次請求將會默認攜帶上。

Docket中有如下兩個方法指定授權信息,分別是securitySchemes()securityContexts()。在配置類中的配置如下,在構建Docket的時候設置進去即可:


 @Bean  public Docket frontApi() {  RequestParameter parameter = new RequestParameterBuilder()  .name("platform")  .description("請求頭")  .in(ParameterType.HEADER)  .required(true)  .build();  List<RequestParameter> parameters = Collections.singletonList(parameter);  return new Docket(DocumentationType.OAS_30)  //是否開啟,根據環境配置  .enable(properties.getFront().getEnable())  .groupName(properties.getFront().getGroupName())  .apiInfo(frontApiInfo())  .select()  //指定掃描的包  .apis(RequestHandlerSelectors.basePackage(properties.getFront().getBasePackage()))  .paths(PathSelectors.any())  .build()  .securitySchemes(securitySchemes())  .securityContexts(securityContexts());  }   /**  * 設置授權信息  */  private List<SecurityScheme> securitySchemes() {  ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());  return Collections.singletonList(apiKey);  }   /**  * 授權信息全局應用  */  private List<SecurityContext> securityContexts() {  return Collections.singletonList(  SecurityContext.builder()  .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))  .build()  );  } 

以上配置成功后,在Swagger文檔的頁面中將會有Authorize按鈕,只需要將請求頭添加進去即可。如下圖:

如何攜帶公共的請求參數?

不同的架構可能發請求的時候除了攜帶TOKEN,還會攜帶不同的參數,比如請求的平台,版本等等,這些每個請求都要攜帶的參數稱之為公共參數。

那么如何在Swagger中定義公共的參數呢?比如在請求頭中攜帶。

Docket中的方法globalRequestParameters()可以設置公共的請求參數,接收的參數是一個List<RequestParameter>,因此只需要構建一個RequestParameter集合即可,如下:

@Bean
public Docket frontApi() {  //構建一個公共請求參數platform,放在在header  RequestParameter parameter = new RequestParameterBuilder()  //參數名稱  .name("platform")  //描述  .description("請求的平台")  //放在header中  .in(ParameterType.HEADER)  //是否必傳  .required(true)  .build();  //構建一個請求參數集合  List<RequestParameter> parameters = Collections.singletonList(parameter);  return new Docket(DocumentationType.OAS_30)  .....  .build()  .globalRequestParameters(parameters);  } 

以上配置完成,將會在每個接口中看到一個請求頭,如下圖:

粗略是一個BUG

作者在介紹自動配置類的時候提到了一嘴,現在來簡單分析下。

OpenApiAutoConfiguration這個自動配置類中已經導入OpenApiDocumentationConfiguration這個配置類,如下一段代碼:

@Import({
 OpenApiDocumentationConfiguration.class,  ...... }) 

@EnableOpenApi的源碼如下:

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = {java.lang.annotation.ElementType.TYPE}) @Documented @Import(OpenApiDocumentationConfiguration.class) public @interface EnableOpenApi { } 

從源碼可以看出:@EnableOpenApi這個注解的作用就是導入OpenApiDocumentationConfiguration這個配置類,納尼???

既然已經在自動配置類OpenApiAutoConfiguration導入了,那么無論需不需要在配置類上標注@EnableOpenApi注解不都會開啟Swagger支持嗎?

測試一下:不在配置類上標注@EnableOpenApi這個注解,看看是否Swagger運行正常。結果在意料之中,還是能夠正常運行。

總結:作者只是大致分析了下,這可能是個BUG亦或是后續有其他的目的,至於結果如此,不想驗證了,沒什么意思。

總結

這篇文章也是嘗了個鮮,個人感覺不太香,有點失望。你喜歡嗎?

Spring Boot 整合的源碼已經上傳,需要的朋友公號回復關鍵詞Swagger3.0獲取。點擊前往


免責聲明!

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



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