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,需同时配置匹配策略和自定义匹配器:
- 在配置文件中指定匹配策略:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
- 编写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
相关产品推荐
相关产品推荐

