先检查一遍swagger扫描开启,enable:true;扫描路径配置正确后仍然还是不显示
springboot2.6+swagger2.9.2无法扫描到接口问题解决
多模块环境下,swaggerConfig配在公共模块,发现部分模块无法扫描到Controller接口。如下图所示:
经检查是部分模块忘记加以下配置了:
spring:mvc:pathmatch:matching-strategy: ant_path_matcher
附上SwaggerConfig(网上找的)
依赖为springfox-boot-starter
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
.enable(true) //是否启用swagger
.apiInfo(apiInfo())
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
// .paths(PathSelectors.any()) //这会把所有路径都给过滤了!
.build();
}
private ApiInfo apiInfo() {
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("标题")
// 描述
.description("描述")
// 作者信息
.contact(new Contact("username", "website", "mail"))
// 版本
.version("版本号:" + "1.0")
.build();
}
/**
* springboot2.6就算配了ant_path_matcher也会和springfox冲突
* 解决springboot2.6 和springfox不兼容问题 Failed to start bean ‘ documentationPluginsBootstrapper ‘ ; nested exception…
*
* @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);
}
}
};
}