Spring Boot整合Knife4j-3.0.3

06-15 1969阅读

文章目录

  • Spring Boot整合Knife4j-3.0.3
    • 1. 引言
    • 2. 快捷的解决方案
      • 2.1 修改knife4j的依赖
      • 2.2 application.yml增加配置
      • 3.3 `SwaggerConfig`配置如下

        Spring Boot整合Knife4j-3.0.3

        1. 引言

        前面我写过一篇关于整合knife4j的文档 Spring Boot整合Knife4j-2.0.7

        Spring Boot整合Knife4j-3.0.3
        (图片来源网络,侵删)

        最近我引入redission的时候莫名其妙的抛出异常:

        Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
        

        原因:

        springboot的版本和Springfox-Swagge的版本不兼容

        2. 快捷的解决方案

        2.1 修改knife4j的依赖

        knife4j依赖

            com.github.xiaoymin
            knife4j-spring-boot-starter
            3.0.3
        
        

        springboot版本

            org.springframework.boot
            spring-boot-starter-parent
            2.7.5
        
        

        2.2 application.yml增加配置

        spring:
          mvc:
            pathmatch:
              matching-strategy: ANT_PATH_MATCHER
        

        这个不能少,否则接口html页面显示不出来

        3.3 SwaggerConfig配置如下

        package com.jiayuan.common.config;
        import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
        import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;
        import com.jiayuan.common.constant.Constant;
        import io.swagger.annotations.ApiOperation;
        import lombok.AllArgsConstructor;
        import org.springframework.beans.BeansException;
        import org.springframework.beans.factory.config.BeanPostProcessor;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.util.ReflectionUtils;
        import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
        import springfox.documentation.builders.ApiInfoBuilder;
        import springfox.documentation.builders.PathSelectors;
        import springfox.documentation.builders.RequestHandlerSelectors;
        import springfox.documentation.service.ApiInfo;
        import springfox.documentation.service.ApiKey;
        import springfox.documentation.service.SecurityScheme;
        import springfox.documentation.spi.DocumentationType;
        import springfox.documentation.spring.web.plugins.Docket;
        import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
        import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
        import springfox.documentation.swagger2.annotations.EnableSwagger2;
        import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
        import java.lang.reflect.Field;
        import java.util.List;
        import java.util.stream.Collectors;
        import static com.google.common.collect.Lists.newArrayList;
        /**
         * Swagger配置
         *
         * @author xmc
         */
        @Configuration
        @EnableSwagger2
        @AllArgsConstructor
        @EnableKnife4j
        public class SwaggerConfig {
            private final OpenApiExtensionResolver openApiExtensionResolver;
            @Bean
            public Docket createRestApi() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .apiInfo(apiInfo())
                        .select()
                        //加了ApiOperation注解的类,生成接口文档
                        .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                        //包下的类,生成接口文档
                        //.apis(RequestHandlerSelectors.basePackage("com.jiayuan.modules.job.controller"))
                        .paths(PathSelectors.any())
                        .build()
                        .extensions(openApiExtensionResolver.buildExtensions("criticalVal-management-system"))
                        .directModelSubstitute(java.util.Date.class, String.class)
                        .securitySchemes(security());
            }
            private ApiInfo apiInfo() {
                return new ApiInfoBuilder()
                        .title("危急值管理系统")
                        .description("cvms-api文档")
                        .version("1.0")
                        .build();
            }
            private List security() {
                return newArrayList(
                        new ApiKey(Constant.TOKEN_HEADER, Constant.TOKEN_HEADER, "header")
                );
            }
            @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  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);
                        }
                    }
                };
            }
        }
        
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]