报错信息:

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

报错过程:

我修改了springboot的版本从2.5.6升到了2.7.11

过后启动springboot出现此错误

报错原因:

SpringBoot2.6.x与Swagger2 3.0.0版本冲突

解决方法:

一、springboot版本降级回2.6以下

二、在application.yml中添加以下配置:

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

                                以上亲测有效~

如果该配置没有启动作用,可以试试下面的配置

@Configuration
@EnableOpenApi
@Slf4j
public class SwaggerConfig implements ApplicationListener<WebServerInitializedEvent> {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(getApiInfo())
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.www.wen"))
                .paths(PathSelectors.any())
                .build();
    }
  
    public ApiInfo getApiInfo(){
        return new ApiInfoBuilder()
                .title("xxx应用平台") // 文档标题
                .description("xxx应用平台文档描述") // 文档描述
                .termsOfServiceUrl("http://www.baidu.com")
                .version("1.0")
                .build();
  
    }
     
    /**
     * 解决SpringBoot和Swagger2冲突
     *
     * @return
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        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) {
                    log.warn("修改WebMvcRequestHandlerProvider的属性:handlerMappings出错,可能导致swagger不可用", e);
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}

Logo

鸿蒙生态一站式服务平台。

更多推荐