Springboot2.7整合knife4j-openapi2-spring-boot报错Failed to start bean ‘documentationPluginsBootstrapper

最近在用Springboot2.7整合knife4j-openapi2-spring-boot-starter后,发现无法启动项目直接报错

报错信息

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

网上解决办法

当时直接搜索引擎一动,解决办法基本上都是添加一个配置。原因是:Spring Boot 2.6以上引入的新PathPatternParser,需要进行配置,不然整合起来会报错

spring.mvc.pathmatch.matching-strategy=ant-path-matcher 

具体问题原因和解决方案

当时以为加上就可以了,结果发现并没有解决问题,问题还是存在,最后网上再次搜索验证,得到的问题原因是和项目引入的其他依赖冲突,当项目当中引入了spring-boot-starter-actuator就会出现这个问题。

可用的解决方案是添加一个bean配置:

	@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) {
	            mappings.removeIf(mapping -> mapping.getPatternParser() != null);
	        }

	        @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);
	            }
	        }
	    };
	}

最后附上解决资料连接:https://gitee.com/xiaoym/knife4j/issues/I4JT89 (没事多看看issues,大佬云集)


标题:Springboot2.7整合knife4j-openapi2-spring-boot报错Failed to start bean ‘documentationPluginsBootstrapper
作者:hjljy
地址:https://www.aliuying.com/articles/2023/07/05/1688523365391.html

评论

  1. 感谢分享

取消