Spring Boot 2.7.3整合Swagger启动失败Failed to start bean ‘documentationPluginsBootstra

652 阅读2分钟

Spring Boot 2.7.3版本引入依赖 springfox-boot-starter (Swagger 3.0) 后,启动容器会报错

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException  
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181)  
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)  
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)  
at java.lang.Iterable.forEach(Iterable.java:75)  
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)  
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)  
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:937)  
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)  
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147)  
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:731)  
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)  
at org.springframework.boot.SpringApplication.run(SpringApplication.java:307)  
at com.foxconn.OaApplication.main(OaApplication.java:20)  
Caused by: java.lang.NullPointerException: null

原因

Springfox 假设 Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6以上版本的默认匹配策略是 path-pattern-matcher,这就造成了上面的报错。

解决方案

方案一(治标)

在 application.yml配置文件中修改mvc的匹配策略:

spring :
  mvc:
    pathmatch:
      matching-strategy: ant-path-matcher

注意:开始的时候我用这个方法的确可以正常启动了,但后来我发现此方法在某些服务启动时会失效!我查了一下才发现这个方法治标不治本,具体如下:

只有在不使用 Spring Boot 的执行器时,此功能才起作用。 无论配置的匹配策略如何,执行器将始终使用基于路径模式的解析 ( 也就是默认策略 ) 。 如果您想在 Spring Boot 2.6及更高版本中将其与执行器一起使用,则需要对 Springfox 进行更改。所以解铃还须系铃人呐!要想彻底解决这个bug,需要修改的是 Springfox 。

方案二(治标)

重写一个 WebMvcConfigurer实现类,然后开启@EnableWebMvc注解:

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
     @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
		//兼容swagger老版本v1,v2
        registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
		registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
    }
}

方案三(治本)

在你的项目启动类添加这个 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) {
                throw new IllegalStateException(e);
            }
        }
    };
}