You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置spring.mvc.pathmatch.matching-strategy兼容Swagger与Actuator

解决Spring Boot中Actuator与SpringFox路径匹配策略兼容问题

问题根源

SpringFox 3.0.0未适配Spring Boot 2.6+引入的path-pattern-matcher新路径匹配策略,当强制配置spring.mvc.pathmatch.matching-strategy = ant-path-matcher时,SpringFox的documentationPluginsBootstrapper bean会因依赖的PatternsRequestCondition为空抛出NPE。而Actuator 2.7.4对两种匹配策略均支持,因此需要调整配置实现二者共存。

两种可行配置方案

方案1:使用默认路径匹配策略(推荐)

将路径匹配策略设为Spring Boot 2.6+默认的path-pattern-matcher,同时配置Actuator使用相同策略,既兼容SpringFox,也保证Actuator正常工作:

# 保持默认策略,适配SpringFox
spring.mvc.pathmatch.matching-strategy = path-pattern-matcher

# 让Actuator使用与Spring MVC一致的路径匹配策略
management.endpoints.web.path-matching.matching-strategy = path-pattern-matcher

此方案无需额外代码,简单直接,且path-pattern-matcher兼容绝大多数Ant风格路径语法,原有接口路径无需修改。

方案2:强制使用Ant路径匹配器(需自定义配置)

如果业务场景必须使用ant-path-matcher,可以通过自定义配置类过滤SpringFox初始化时的空条件,避免触发空指针异常:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;

import java.util.List;
import java.util.stream.Collectors;

@Configuration
public class SpringFoxCompatibilityConfig {

    @Bean
    public DocumentationPluginsBootstrapper documentationPluginsBootstrapper(List<RequestMappingHandlerMapping> handlerMappings) {
        // 过滤掉没有PatternsRequestCondition的HandlerMapping,避免空指针
        List<RequestMappingHandlerMapping> validMappings = handlerMappings.stream()
                .filter(mapping -> mapping.getPatternsCondition() != null)
                .collect(Collectors.toList());
        return new DocumentationPluginsBootstrapper(new WebMvcRequestHandlerProvider(validMappings));
    }
}

同时保留原有配置:

spring.mvc.pathmatch.matching-strategy = ant-path-matcher
management.endpoints.web.path-matching.matching-strategy = ant-path-matcher

额外建议

SpringFox 3.0.0已停止维护,长期来看建议迁移至SpringDoc OpenAPI(Spring官方推荐的Swagger替代方案),彻底规避版本兼容问题。

内容的提问来源于stack exchange,提问作者Caesarius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:30:45