SpringBoot 2.7.15如何通过代码配置ANT_PATH_MATCHER适配Swagger-ui3.0
在Spring Boot 2.7.15中代码配置ANT_PATH_MATCHER适配Swagger UI 3.0.0
可行的代码配置方案
你可以通过实现WebMvcConfigurer接口并调整路径匹配配置,替代配置文件的设置,且无需使用@EnableWebMvc:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class SwaggerPathMatchConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { // 禁用默认的PathPatternParser,切换为AntPathMatcher模式 configurer.setPatternParser(null); // 设置具体的路径匹配器实现 configurer.setPathMatcher(new org.springframework.util.AntPathMatcher()); } }
另一种更直接的配置方式是通过WebMvcProperties指定匹配策略:
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class WebMvcConfig { @Bean public WebMvcProperties webMvcProperties() { WebMvcProperties properties = new WebMvcProperties(); properties.getPathmatch().setMatchingStrategy(WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER); return properties; } }
为什么之前的配置未生效
你之前仅重写configurePathMatch方法设置AntPathMatcher,但Spring Boot 2.7.x默认启用PathPatternParser(对应PATH_PATTERN_PARSER匹配策略),此时即使设置了PathMatcher,Spring MVC依然会优先使用PathPatternParser处理路径。必须显式禁用PathPatternParser(设置setPatternParser(null)),或者直接指定匹配策略为ANT_PATH_MATCHER,才能让AntPathMatcher真正生效。
内容的提问来源于stack exchange,提问作者rhbc73
相关产品推荐
相关产品推荐

