一、 了解官方最新資料
截止到 2021年04月,Springfox 的 Swagger2 依賴版本最高到 3.0.0。
但至少在 2.10.5 版本就已經(jīng)有了不少變化,比如找不到 @EnableSwagger2 的注解了等等。
先到Springfox GH地址:https://github.com/springfox/springfox
看 Getting Started, 終于有 swagger 的 starter 了, Spring Boot 用戶更方便集成了
可以看到主要變動:
- Remove explicit dependencies on
springfox-swagger2 - Remove the
@EnableSwagger2annotations - Add the
springfox-boot-starterdependency - Springfox 3.x removes dependencies on guava and other 3rd party libraries (not zero dep yet! depends on spring plugin and open api libraries for annotations and models) so if you used guava predicates/functions those will need to transition to java 8 function interfaces
...
大意為
- 移除
springfox-swagger2的顯式依賴 (個人理解是用新的依賴不需要添加這個舊的springfox-swagger2依賴了) - 移除了
@EnableSwagger2注解 (這是與之前版本明顯區(qū)別的地方) - 新增了 starter 方式的依賴
- Springfox 3.x 版本移除了 guava 和其它一些第三方庫 (不過尚未完全移除), 如果使用 guava 庫的斷言/函數(shù)式接口功能的需要過渡到 java 8 的函數(shù)式接口
...
二、記錄新的集成方式
1. POM
大部分內(nèi)容依然沒變,唯一不同的是依賴。與 Springboot 集成可用新的依賴:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
2. 配置類
SwaggerConfig.java(不需要 @EnableSwagger2 了)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("org.example.consumer.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* Api 文檔詳細信息
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Title")
.contact(new Contact("name", "url", "email"))
.version("1.0.0")
.description("description")
.build();
}
}
最簡配置只需以上兩步即可。
URL: http://127.0.0.1:8990/swagger-ui/index.html
(8990 是我配置的項目端口)
三、SpringBoot 2.6.x 集成的問題
SpringBoot 2.6.x 在集成時會報錯:
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
經(jīng)過深層 debug,我發(fā)現(xiàn)根本原因是 SpringBoot 2.6 的換了 MVC 的路徑匹配策略, 由 ANT_PATH_MATCHER 換成了 PATH_PATTERN_PARSER。
解決方案:
等 Swagger 適配 SpringBoot 2.6;
自己改 Swagger 的代碼打本地包適配;
使用 2.6 之前的 SpringBoot 版本;
-
在 application.yml 中將配置策略改回
ANT_PATH_MATCHER:spring: mvc: pathmatch: matching-strategy: ant_path_matcher