SpringBoot 2.6.x高版本和swagger2版本冲突升级版本

1. 使用swagger3.0版本以前的可以参考我的上篇文章解决

SpringBoot2.6.x高版本与swagger2版本冲突问题解决

2. 现在使用swagger 3.0版本的解决方案: (仅3步)

2.1 : 添加 SwaggerBeanPostProcessor

@Component
public class SwaggerBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider)
        {
            List handlerMappings = getHandlerMappings(bean);
            customizeSpringfoxHandlerMappings(handlerMappings);
        }
        return bean;
    }

    private  void customizeSpringfoxHandlerMappings(List mappings) {
        List copy = mappings.stream()
                .filter(mapping -> mapping.getPatternParser() == null)
                .collect(Collectors.toList());
        mappings.clear();
        mappings.addAll(copy);
    }

    @SuppressWarnings("unchecked")
    private List getHandlerMappings(Object bean) {
        try {
            Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
            field.setAccessible(true);
            return (List) field.get(bean);
        }
        catch (IllegalArgumentException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }
}

 2.2: 添加swagger3Config

@Configuration
@EnableOpenApi // 注意添加此注解
public class Swagger3Config {


    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("Swagger3接口文档")
                .description("适用于前后端分离统一的接口文档")
                .version("1.0")
                .build();
    }

}

3. 配置文件中添加: spring.mvc.pathmatch.matching-strategy=ant-path-matcher

你可能感兴趣的:(spring,boot,java,spring,boot)