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 @ 2024-06-12 20:27  郭培鑫同学  阅读(5)  评论(0编辑  收藏  举报