目录
问题
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
原因
方案一(治标)[本人用了方案一解决了]
在 application.yml配置文件中修改mvc的匹配策略:
spring :
mvc:
pathmatch:
matching-strategy: ant-path-matcher
方案二(治标)
重写一个 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);
}
}
注意:这种方法会破坏sprijngboot自带的mvc自动装配配置项,导致默认的一些静态目录功能无法使用,只能重写addResourceHandlers方法,需要手动把静态目录指定一下
在Spring Boot 2.7.2版本中,查看默认静态资源路径,在WebProperties.class
中如下
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
方案三(治本)
这个办法是我在 github 上找到的,一个大佬提了一个解决方案是将 Springfox 的某 .java 文件复制到自己项目里进行修改,另一个大佬提了一个更好的解决方案,我觉得真不错,在这里分享一下:
在你的项目里添加这个 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) {
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);
}
}
};
}
希望以上3个方案对你有所帮助,点个关注呗!