SpringBoot2.6.9集成Swagger3配置ant_path_matcher仍报空指针异常
问题场景
- 技术栈版本:Spring Boot 2.6.9,Springfox Swagger 3.0.0
- 已添加配置:在测试环境yml配置中写入了路径匹配规则,配置内容如下:
spring: mvc: pathmatch: matching-strategy: ant_path_matcher
- 报错现象:运行单元测试时抛出空指针异常,核心异常栈信息如下:
Caused by: java.lang.NullPointerException: null at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
遗漏配置与修复步骤
这个空指针是Springfox 3.0.0对Spring Boot 2.6+版本的测试场景适配缺陷导致的,仅配置路径匹配策略不足以覆盖测试上下文的初始化要求,按以下顺序补全配置即可解决:
- 确认测试类注解配置正确
- 若使用
@WebMvcTest做Web层切片测试:该注解默认不会加载Swagger相关的自动配置类,会导致Springfox的WebMVC组件初始化不全触发空指针,需要手动指定加载Springfox的WebMVC配置类,示例:
@WebMvcTest( controllers = YourTargetController.class, includeFilters = @ComponentScan.Filter( type = FilterType.ASSIGNABLE_TYPE, classes = SpringfoxWebMvcConfiguration.class ) )- 若使用
@SpringBootTest做全上下文测试:不要将web环境设置为WebEnvironment.NONE,必须指定为模拟Servlet环境,示例:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) - 若使用
- 确保测试配置文件被正确加载
如果你添加的路径匹配配置写在application-test.yml这类专属测试的配置文件中,必须在测试类上添加@ActiveProfiles("test")注解激活对应profile,否则测试启动时仍会使用Spring Boot 2.6默认的PathPatternParser匹配策略,和Springfox 3.0.0不兼容。 - 补全Swagger基础配置类
仅靠yml配置无法完成Springfox初始化,必须手动注册Docket类型的Bean,基础配置示例:@Configuration @EnableOpenApi public class SwaggerConfig { @Bean public Docket docket() { return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("替换为你项目的Controller包全路径")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("项目接口文档") .version("1.0") .build(); } } - 排查依赖冲突
检查项目pom/gradle配置,不要同时引入springfox-boot-starter和旧版的springfox-swagger2、springfox-swagger-ui依赖,重复引入会导致类加载异常触发空指针,仅保留springfox-boot-starter 3.0.0即可。
内容的提问来源于stack exchange,提问作者Harshana
相关产品推荐
相关产品推荐

