【亲测】Spring Boot 2.6.x整合Swagger启动失败报错问题解决(永久久久解决)
本文参考:
toollong原文链接:https://blog.csdn.net/weixin_49523761/article/details/122305980
亲测好使,欢迎同学们验证。
更多的视频教程参考:
SpringCloud+Oauth2+Vue+ElementUI前后端分离快速上手项目实战开发--Java视频教程-编程语言-CSDN程序员研修院
问题
Spring Boot 2.6.x版本引入依赖 springfox-boot-starter (Swagger 3.0) 后,启动容器会报错:
Failed to start bean ‘ documentationPluginsBootstrapper ‘ ; nested exception…
原因
Springfox 假设 Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6.x版本的默认匹配策略是 path-pattern-matcher,这就造成了上面的报错。
解决方案
方案一(治标)
在 application.properties 配置文件中修改mvc的匹配策略:
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
注意:开始的时候我用这个方法的确可以正常启动了,但后来我发现此方法在某些服务启动时会失效!我查了一下才发现这个方法治标不治本,具体如下:
只有在不使用 Spring Boot 的执行器时,此功能才起作用。
无论配置的匹配策略如何,执行器将始终使用基于路径模式的解析 ( 也就是默认策略 ) 。
如果您想在 Spring Boot 2.6及更高版本中将其与执行器一起使用,则需要对 Springfox 进行更改。
所以解铃还须系铃人呐!要想彻底解决这个bug,需要修改的是 Springfox 。
方案二(治本)
这个办法是我在 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);
}
}
};
}
启动成功,完美解决,这样就不需要修改mvc的匹配策略了。
完整配置类:
/*
* 高薪启蒙 csdn学院地址:https://edu.csdn.net/lecturer/1141?spm=1002.2001.3001.4144
* Array老师:https://edu.csdn.net/course/detail/29600
*/
package com.qimeng.common.swagger;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Swagger 配置相关
*/
@Configuration
@EnableSwagger2
@EnableKnife4j
public class SwaggerConfiguration implements WebMvcConfigurer {
/**
* 注入资源文件
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars*")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public Docket docketApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.qimeng"))
.paths(PathSelectors.any())
.build();
}
/**
* API详情配置
*/
private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
.title("Libra-Platform接口文档")
.description("<div style='font-size:14px;color:red;'>knife4j swagger RESTful APIs</div>")
.version("1.0")
.build();
}
/**
* 解决springboot2.6 和springfox不兼容问题
* @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) {
throw new IllegalStateException(e);
}
}
};
}
}
再次感谢
原文链接:https://blog.csdn.net/weixin_49523761/article/details/122305980
相关文章
- 使用Spring boot整合Hive,在启动Spring boot项目时,报错
- spring boot 之 spring security 配置
- Spring中使用RedisTemplate操作Redis(spring-data-redis)
- Spring Boot 2.x :通过 spring-boot-starter-hbase 集成 HBase
- spring boot:解决cors跨域问题的两种方法(spring boot 2.3.2)
- Spring Boot下配置MyBatis多数据源
- Spring Boot——2分钟构建spring web mvc REST风格HelloWorld
- Spring Boot 2.3.x 分层构建 Docker 镜像实战
- spring学习12 -Spring 框架模块以及面试常见问题注解等
- 将Spring Boot作为守护进程启动的一种简单的方法
- Spring boot应用如何支持https
- 已解决:解决 Spring Boot 多线程环境下,多个定时器冲突问题
- Spring Boot集成Druid出现异常报错的原因及解决
- spring boot报FileSizeLimitExceededException异常的解决方法
- Spring Boot 之spring.factories
- 学习Spring Boot:(四)应用日志
- spring boot pom.xml 提示 ignored 具体解决
- 全网最完美地解决使用spring boot的@Value(“${xxx}“)注解时报出的错误:Could not resolve placeholder ‘xxx‘ in value “${xxx}“
- 一文详说Spring Boot集成RabbitMQ,细说消息队列常用5种模式,消息持久化,两种延迟发送的机制以及解决Spring Boot集成RabbitMQ的常见问题
- RabbitMQ与Spring的框架整合之Spring Boot实战
- struts2+hibernate+spring注解版框架搭建以及简单测试(方便脑补)
- java经典面试题之Spring Boot 面试题汇总附答案(史上最全持续更新)
- Spring Cloud Alibaba 异步通信 - RocketMQ 生产者
- [spring学习]8、@Autowired和@Resource的区别