解决springboot2.6和swagger冲突的四种方法
最近要将后台服务从SpringBoot1升级到2版本,主要目的是为了使用SpringBoot2的实时监控功能。集成的时候无法启动,根据日志判断与swagger有关。查了半天,一个解释是springboot修改了请求路由匹配策略,Spring MVC 处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser。Actuator端点现在也使用基于 P
最近要将后台服务从SpringBoot1升级到2版本,主要目的是为了使用SpringBoot2的实时监控功能。集成的时候无法启动,根据日志判断与swagger有关。信息如下:
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) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13]
at java.lang.Iterable.forEach(Iterable.java:75) ~[?:?]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.1.jar:2.6.1]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-2.6.1.jar:2.6.1]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412) ~[spring-boot-2.6.1.jar:2.6.1]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) ~[spring-boot-2.6.1.jar:2.6.1]
at com.iscas.biz.BizApp.main(BizApp.java:69) ~[classes/:?]
Caused by: java.lang.NullPointerException
at springfox.documentation.spring.web.WebMvcPatternsRequestConditionWrapper.getPatterns(WebMvcPatternsRequestConditionWrapper.java:56) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
at springfox.documentation.RequestHandler.sortedPaths(RequestHandler.java:113) ~[springfox-core-3.0.0.jar:3.0.0]
at springfox.documentation.spi.service.contexts.Orderings.lambda$byPatternsCondition$3(Orderings.java:89) ~[springfox-spi-3.0.0.jar:3.0.0]
at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469) ~[?:?]
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[?:?]
at java.util.TimSort.sort(TimSort.java:234) ~[?:?]
at java.util.Arrays.sort(Arrays.java:1515) ~[?:?]
at java.util.ArrayList.sort(ArrayList.java:1750) ~[?:?]
at java.util.stream.SortedOps$RefSortingSink.end(SortedOps.java:392) ~[?:?]
at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
at java.util.stream.Sink$ChainedReference.end(Sink.java:258) ~[?:?]
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485) ~[?:?]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[?:?]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[?:?]
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:?]
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[?:?]
at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:81) ~[springfox-spring-webmvc-3.0.0.jar:3.0.0]
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195) ~[?:?]
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655) ~[?:?]
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[?:?]
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[?:?]
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[?:?]
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[?:?]
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[?:?]
at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.withDefaults(AbstractDocumentationPluginsBootstrapper.java:107) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.buildContext(AbstractDocumentationPluginsBootstrapper.java:91) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at springfox.documentation.spring.web.plugins.AbstractDocumentationPluginsBootstrapper.bootstrapDocumentationPlugins(AbstractDocumentationPluginsBootstrapper.java:82) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:100) ~[springfox-spring-web-3.0.0.jar:3.0.0]
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.13.jar:5.3.13]
... 12 more
查了半天,一个解释是springboot修改了请求路由匹配策略,
Spring MVC 处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser。Actuator端点现在也使用基于 PathPattern 的 URL 匹配,因此Actuator端点的路径匹配策略无法通过配置属性进行配置。
我采用的方法
如果需要将默认切换回 AntPathMatcher,可以将 spring.mvc.pathmatch.matching-strategy 设置为 ant-path-matcher,比如下面这样:
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
一种解决办法是手动创建一个配置类,来修改路由规则,在你工程创建一个包:
springfox.documentation.spring.web.plugins
注意这里必须使用上面的包名,这样才 能代替springfox自带的。
然后创建一个类,完整代码如下:
/**
* springboot升级到2.6后和swagger出现冲突,这是springboot修改了请求路由匹配策略造成的。
* Spring MVC 处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser,导致swagger加载失败,
* 这里手动设置一下
*/
package springfox.documentation.spring.web.plugins;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.BuilderDefaults;
import springfox.documentation.spi.service.RequestHandlerProvider;
import springfox.documentation.spi.service.contexts.Orderings;
import springfox.documentation.spring.web.WebMvcRequestHandler;
import springfox.documentation.spring.web.readers.operation.HandlerMethodResolver;
import javax.servlet.ServletContext;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static springfox.documentation.spring.web.paths.Paths.ROOT;
@Component
@Order(-2147483648)
public class WebMvcRequestHandlerProvider implements RequestHandlerProvider {
private final List<RequestMappingInfoHandlerMapping> handlerMappings;
private final HandlerMethodResolver methodResolver;
private final String contextPath;
@Autowired
public WebMvcRequestHandlerProvider(Optional<ServletContext> servletContext, HandlerMethodResolver methodResolver, List<RequestMappingInfoHandlerMapping> handlerMappings) {
this.handlerMappings = handlerMappings.stream().filter(mapping -> Objects.isNull(mapping.getPatternParser())).collect(Collectors.toList());
this.methodResolver = methodResolver;
this.contextPath = servletContext
.map(ServletContext::getContextPath)
.orElse(ROOT);
}
public List<RequestHandler> requestHandlers() {
return (List)BuilderDefaults.nullToEmptyList(this.handlerMappings).stream().filter((requestMappingInfoHandlerMapping) -> {
return !"org.springframework.integration.http.inbound.IntegrationRequestMappingHandlerMapping".equals(requestMappingInfoHandlerMapping.getClass().getName());
}).map(this.toMappingEntries()).flatMap((entries) -> {
return StreamSupport.stream(entries.spliterator(), false);
}).map(this.toRequestHandler()).sorted(Orderings.byPatternsCondition()).collect(Collectors.toList());
}
private Function<RequestMappingInfoHandlerMapping, Iterable<Entry<RequestMappingInfo, HandlerMethod>>> toMappingEntries() {
return (input) -> {
return input.getHandlerMethods().entrySet();
};
}
private Function<Entry<RequestMappingInfo, HandlerMethod>, RequestHandler> toRequestHandler() {
return (input) -> {
return new WebMvcRequestHandler(this.contextPath, this.methodResolver, (RequestMappingInfo)input.getKey(), (HandlerMethod)input.getValue());
};
}
}
上面代码的核心是修改了构造器的实现代码,你可以与原始的对照一下,就是把不符合规则的控制器过滤器掉了。
这样就能解决问题了。
网上还有人说这样解决不优雅,其他的方式没有使用,这里一起附上,供你参考:
第二种参考方法
添加一个BeanPostProcessor,在postProcessAfterInitialization中修改WebMvcRequestHandlerProvider中的handlerMappings属性,这种方式其实更第一种是一样的,这样不用覆盖原有类,更优雅一些。
package com.iscas.biz.config;
/**
* 自定义BeanPostProcessor
*
* @author zhuquanwen
* @version 1.0
* @date 2021/12/29
* @since jdk11/
*/
@SuppressWarnings({"unused", "unchecked"})
@Component
@Slf4j
public class MyBeanPostProcessor implements BeanPostProcessor {
@Autowired
private DefaultListableBeanFactory defaultListableBeanFactory;
@Override
public Object postProcessBeforeInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
handleWebMvcRequestHandlerProvider(beanName, bean);
return bean;
}
private void handleWebMvcRequestHandlerProvider(String beanName, Object bean) {
// 处理swagger 在spring boot2.6以上不可用的问题
boolean modify = (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) &&
defaultListableBeanFactory.containsBean(beanName);
if (modify) {
// 修改属性
try {
Field handlerMappingsField = bean.getClass().getDeclaredField("handlerMappings");
ReflectUtils.makeAccessible(handlerMappingsField);
List<RequestMappingInfoHandlerMapping> handlerMappings = (List<RequestMappingInfoHandlerMapping>) handlerMappingsField.get(bean);
List<RequestMappingInfoHandlerMapping> tmpHandlerMappings = handlerMappings.stream().filter(mapping -> Objects.isNull(mapping.getPatternParser())).collect(Collectors.toList());
handlerMappings.clear();
handlerMappings.addAll(tmpHandlerMappings);
} catch (Exception e) {
log.warn("修改WebMvcRequestHandlerProvider的属性:handlerMappings出错,可能导致swagger不可用", e);
}
}
}
}
ReflectUtils.makeAccessible的方法:
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) ||
!Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
第三种解决办法
这种是最优雅的方式,我测试时发现并没有生效,暂且一起附上吧,希望对你有用:
注册一个WebMvcEndpointHandlerMapping类。
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier,
ServletEndpointsSupplier servletEndpointsSupplier,
ControllerEndpointsSupplier controllerEndpointsSupplier,
EndpointMediaTypes endpointMediaTypes,
CorsEndpointProperties corsProperties,
WebEndpointProperties webEndpointProperties,
Environment environment) {
List<ExposableEndpoint<?>> allEndpoints = new ArrayList<>();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
String basePath = webEndpointProperties.getBasePath();
EndpointMapping endpointMapping = new EndpointMapping(basePath);
boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(),
new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
}
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) ||
ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}
之后在另外一个工程又遇到了类似的情况,但是上面的三种都不好使,所以又找到了第四种解决方法:
第四种方法
在你的工程里创建一个配置类,内容如下:
package com.fenbi.im.service.config;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.actuate.autoconfigure.web.server.ManagementPortType;
import org.springframework.boot.actuate.endpoint.ExposableEndpoint;
import org.springframework.boot.actuate.endpoint.web.*;
import org.springframework.boot.actuate.endpoint.web.annotation.ControllerEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.annotation.ServletEndpointsSupplier;
import org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/***
* @date 2022/10/26
* author https://blog.csdn.net/xueyushenzhou?type=blog
*/
@Configuration
public class SpringFoxSwaggerConfig {
/**
* 配置基本信息
*
* @return
*/
@Bean
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger Test App Restful API")
.description("swagger test app restful api")
.termsOfServiceUrl("test")
.contact(new Contact("haha", "https://blog.csdn.net/xueyushenzhou?type=blog", "abc@hotmail.com"))
.version("1.0")
.build();
}
/**
* 配置文档生成最佳实践
*
* @param apiInfo
* @return
*/
@Bean
public Docket createRestApi(ApiInfo apiInfo) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.groupName("SwaggerGroupOneAPI")
.select()
.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
.paths(PathSelectors.any())
.build();
}
/**
* 增加如下配置可解决Spring Boot 6.x 与Swagger 3.0.0 不兼容问题
**/
@Bean
public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier, ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier, EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties, WebEndpointProperties webEndpointProperties, Environment environment) {
List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
allEndpoints.addAll(webEndpoints);
allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
String basePath = webEndpointProperties.getBasePath();
EndpointMapping endpointMapping = new EndpointMapping(basePath);
boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment, basePath);
return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes, corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath), shouldRegisterLinksMapping, null);
}
private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment, String basePath) {
return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath) || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
}
}
这样也能解决,懒得研究原理,干脆都记下吧
祝你顺利!
更多推荐
所有评论(0)