Swagger2和Springboot版本不对应报错以及解决方案

文章描述了一个在使用Springboot2.7.5和Swagger3.0.0时遇到的ApplicationContextException问题,原因是Springfox的路径匹配与Spring2.6+的PathPatternMatcher不兼容。提供了两种解决方案:一是降级Springboot和Swagger到兼容版本(如2.5.6和2.9.2),二是通过配置更改Spring的路径匹配策略为AntPathMatcher,或者使用BeanPostProcessor修改Springfox的HandlerMappings。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


由于使用的swagger2与spring版本不对应,如下引起了报错:
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

1.问题详情

swagger2版本为3.0.0
Springboot版本为2.7.5
仅做了@EnableSwagger2、Docket的注入,运行后报错;

2.原因分析

这是因为在Springfox中,使用AntPathMatcher来完成路径匹配,在Spring2.6.X以及以上,使用PathPatternMatcher完成匹配,从而导致引用配置路径为空引起NPE

3.解决方案

3.1解决方案一,springboot、swagger使用较低版本

spring boot 2.5.6 + swagger2.9.2是可行的

3.2 解决方案二,不降低版本

spirngbootswagger
2.7.53.0.0(springfox-boot-starter)

第一步:application.yml需要添加如下配置:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

第二步:
方案一:自行配置WebMvcEndpointHandlerMapping的Bean

@Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
    }
    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }

方案二:在Bean完成注入后修改WebMvcEndpointHandlerMapping的Bean配置(BeanPostProcessor)

    public BeanPostProcessor generateBeanPostProcessor(){
        return new BeanPostProcessor() {

            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值