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

Spring Boot 3.x RESTful服务URL不区分大小写配置求助

Spring Boot 3.x 实现URL不区分大小写的有效方案

针对Spring Boot 3.1.4 + spring-boot-starter-web 3.2.X版本,以下是经过验证的有效方案,同时解释之前方案失效的原因:

原因分析

Spring Boot 3.x 默认使用 PathPatternParser 作为路径匹配器,而非旧版的 AntPathMatcher。之前的方案失效主要是因为:

  • 方案一仅切换了匹配策略,但未配置对应匹配器的大小写敏感属性;
  • 方案二自定义了 AntPathMatcher,但未指定匹配策略为 ant_path_matcher,默认仍使用 PathPatternParser,自定义匹配器未生效;
  • 方案三使用废弃的 WebMvcConfigurerAdapter 且添加了 @EnableWebMvc,该注解会禁用Spring Boot的Web自动配置,导致路径匹配规则冲突。

有效方案

方案1:使用默认的PathPatternParser配置(推荐)

无需自定义类,直接在配置文件中修改 PathPatternParser 的大小写敏感配置:

application.properties

spring.mvc.pathmatch.path-pattern-parser.case-sensitive=false

application.yml

spring:
  mvc:
    pathmatch:
      path-pattern-parser:
        case-sensitive: false

方案2:切换为AntPathMatcher并配置大小写不敏感

如果需要沿用 AntPathMatcher,需同时配置匹配策略和自定义匹配器:

  1. 在配置文件中指定匹配策略:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
  1. 编写WebMvc配置类(不要加@EnableWebMvc):
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        pathMatcher.setCaseSensitive(false);
        configurer.setPathMatcher(pathMatcher);
    }

    // 保留你的CORS配置
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*");
    }
}

注意事项

  • 不要在配置类中添加 @EnableWebMvc,该注解会完全接管Spring MVC的配置,覆盖Spring Boot的自动配置,导致路径匹配等规则失效;
  • 优先使用方案1,因为 PathPatternParser 是Spring Boot 3.x推荐的路径匹配器,性能和功能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:20:11