Springfox 3.0.0 与 Spring Boot 2.6.0 不兼容启动报错问题求助
Spring Boot 2.6+ 与 Springfox 3.0.0 兼容问题解决方案
问题根因
Spring Boot 从2.6.0版本开始,默认将Spring MVC的路径匹配策略从AntPathMatcher调整为PathPatternParser,而Springfox 3.0.0 早已停止维护,未适配新的路径匹配规则,初始化时无法正常获取请求路径条件,因此抛出空指针异常。
解决方案
方案1:调整路径匹配策略(临时兼容方案)
无需修改依赖,仅需修改配置即可快速修复:
- 在项目配置文件中修改Spring MVC路径匹配策略:
若使用application.yml,添加如下配置:
若使用spring: mvc: pathmatch: matching-strategy: ant_path_matcherapplication.properties,添加如下配置:spring.mvc.pathmatch.matching-strategy=ant_path_matcher - 若项目同时整合了Actuator组件,修改配置后仍报错,可在Swagger配置类中添加如下Bean:
@Bean public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) { List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>(); Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints(); allEndpoints.addAll(webEndpoints); allEndpoints.addAll(servletEndpointsSupplier.getEndpoints()); allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints()); String basePath = webEndpointProperties.getBasePath(); EndpointMapping endpointMapping = new EndpointMapping(basePath); boolean shouldRegisterLinksMapping = webEndpointProperties.getDiscovery().isEnabled() && (org.springframework.util.StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT)); return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null); }
方案2:替换为SpringDoc(长期推荐方案)
Springfox已经停止维护多年,无法兼容后续更高版本的Spring Boot(如2.7+、3.x版本),推荐替换为仍在持续维护的SpringDoc OpenAPI作为接口文档工具,迁移成本很低:
- 第一步:移除所有Springfox相关依赖(包括
springfox-boot-starter、springfox-swagger2、springfox-swagger-ui等) - 第二步:引入对应版本的SpringDoc依赖,Spring Boot 2.x版本引入如下依赖:
Maven配置:
Gradle配置:<dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.6.15</version> </dependency>implementation 'org.springdoc:springdoc-openapi-ui:1.6.15' - 第三步:调整原有Swagger注解即可正常使用,核心注解对应关系如下:
@Api→@Tag@ApiOperation→@Operation@ApiModel→@Schema@ApiModelProperty→@Schema
内容的提问来源于stack exchange,提问作者Thirumal
相关产品推荐
相关产品推荐

