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

目錄
-
前言 -
官方文檔如何說? -
Spring Boot版本說明 -
添加依賴 -
springfox-boot-starter做了什么? -
擼起袖子就是干? -
定制一個基本的文檔示例 -
文檔如何分組? -
如何添加授權信息? -
如何攜帶公共的請求參數?
-
-
粗略是一個BUG -
總結
前言
最近頻繁被Swagger 3.0
刷屏,官方表示這是一個突破性的變更,有很多的亮點,我還真不太相信,今天來帶大家嘗嘗鮮,看看這碗湯到底鮮不鮮....
官方文檔如何說?
該項目開源在Github
上,地址:https://github.com/springfox/springfox。
Swagger 3.0
有何改動?官方文檔總結如下幾點:
-
刪除了對 springfox-swagger2
的依賴 -
刪除所有 @EnableSwagger2...
注解 -
添加了 springfox-boot-starter
依賴項 -
移除了 guava
等第三方依賴 -
文檔訪問地址改變了,改成了 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
)。

「重點」:記住
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端
,小程序端
.....每個端的接口可能還相同,不可能全部放在一起吧,肯定是要區分開的。
因此,實際開發中文檔肯定是要分組的。
分組其實很簡單,Swagger
向IOC
中注入一個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」獲取。點擊前往
