升级boot版本至2.6.x的变化之swagger

/ 技术收藏 / 没有评论 / 469浏览

由于近期springboot爆发了一系列高危漏洞,遂也决定把boot和其他一些依赖一并升级一下。升级后首先就是项目无法启动了,报错如下:

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

根据堆栈信息,应该是spring mvc处理程序映射匹配请求路径的默认策略已从 AntPathMatcher 更改为PathPatternParser,看来是springfox没有适配路径策略的问题,于是带着问题直接找到了springfox的github主页( https://github.com/springfox/springfox/issues ),发现果然一堆关于升级2.6.x的issue,再看看项目基本两年多没更新了,看样子指望springfox更新适配2.6+暂时是不用指望了,临时的解决方案也比较暴力,通过反射获取到bean的属性,直接修改。 方法如下(通过bean的后置处理器)

修改yml

spring:  
  mvc:
    pathmatch:
      matching-strategy: ANT_PATH_MATCHER #springfox未更新,和springboot2.6+冲突

添加一个bean的后置处理器(如果没有引入springboot的端点,这一步可以不要)

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
            List<RequestMappingInfoHandlerMapping> handlerMappings = getHandlerMappings(bean);
            customizeSpringfoxHandlerMappings(handlerMappings);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    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);
        }
    }