升级Spring boot到2.7之后,启动的时候遇到Swagger的报错问题:
Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
遍查网络后发现所谓的解决,都是特定的局限场景:要么是没有使用spring boot actuator, 要么是没解决swagger-ui打开的问题。兼顾上面完整诉求的关键步骤如下。
- springfox直接用最新版3.0.0,直接使用 `springfox-boot-starter` 不然不会有ui对应的mapping。注意mapping的路径为/swagger-ui/,不是swagger-ui.html
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId> <!-- 自动注册 /swagger-ui/ 的路由 -->
<version>3.0.0</version>
</dependency>
- 配置mvc的path match策略为“ANT_PATH_MATCHER”:
spring:
mvc:
pathmatch:
matching-strategy: ANT_PATH_MATCHER
- (最复杂的一步,不使用actuator的不需要)配置spring-boot-actuator的路径策略,注册HandlerMapping:
@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));
}