springboot2.6x集成swagger2踩坑点

最近在用springBoot2.6.13集成swagger2.9.2时出现了几个bug,经过几番尝试后,得出了最终的结论,时间紧可以直接看结论。

首次集成swagger2时,启动springboot后的bug:

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

经过网上查找发现: springboot版本与swagger2不兼容导致的问题。

第一个解决方案:降低springboot版本为2.5.5

第二个解决方案:升级swagger2为3

其实这两种都不太方便,牵一发而动全身,不采取。

经过翻阅springBoot2.6源码,发现底层的路径匹配变量有了变化:

2.6.0开始使用基于PathPatternParser的路径匹配,而Springfox版本一直没有更新还是使用的AntPathMatcher导致了这个问题。

所以有了第三种解决方案:将SpringBoot路径匹配模式进行修改

修改yaml文件,yaml的配置如下:

spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER

或者修改properties文件配置:

spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER

其他解决方案:首先在启动类上使用注解@EnableWebMvc,其次在swagger配置类中需要添加WebMvcConfigurerAdapter方法,但是这样有个弊端:springBoot提供的自动化功能都失效了,因为@EnableWebMvc会全部接管springboot的webMvcXConfiguer。

@Configuration
@EnableSwagger2
public class swaggerConfig {
@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter() {
return new WebMvcConfigurerAdapter() {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html**")
.addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
};
}
}

总结:为了兼容swagger2,在不必降低springBoot2.6版本的情况下,修改SpringBoot底层的springMVC的路径匹配模式为ANT_PATH_MATCHER。

参考资料:https://springboot.io/t/topic/4972

posted @   gdxstart  阅读(134)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
历史上的今天:
2023-06-12 2反转字符
2023-06-12 事务操作
2023-06-12 1替换字符
点击右上角即可分享
微信分享提示