• spring-boot2.6.x兼容swagger2问题


    spring-boot2.6.x兼容swagger2问题

    更改spring-boot2.6.x版本的默认匹配策略

    springfox 使用的是 ant_path_matcher 匹配策略

    spring:
    # ant_path_matcher、(spring-boot2.6.x默认匹配策略)path-pattern-matcher
      mvc:
        pathmatch:
          matching-strategy: ant_path_matcher
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    依赖

    		<!--swagger2-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-boot-starter</artifactId>
                <version>3.0.0</version>
            </dependency>
            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>swagger-bootstrap-ui</artifactId>
                <version>1.9.6</version>
            </dependency>
            
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    SwaggerBeanPostProcessor 配置

    package cn.springboot.model.base.config;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    import org.springframework.stereotype.Component;
    import org.springframework.util.ReflectionUtils;
    import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
    import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
    import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
    
    import java.lang.reflect.Field;
    import java.util.List;
    import java.util.stream.Collectors;
    
    /**
     * 兼容 springboot 2.6.x 处理
     *
     * @author jf
     */
    @Component
    public class SwaggerBeanPostProcessor implements 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");
                assert field != null;
                field.setAccessible(true);
                return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    SwaggerConfig 配置

    package cn.springboot.model.base.config;
    
    import io.swagger.models.auth.In;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.util.ResourceUtils;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.*;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * Swagger2 的接口配置
     *
     * @author jf
     */
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig implements WebMvcConfigurer {
        /**
         * 系统基础配置
         */
        @Autowired
        private ModelConfig modelConfig;
    
        /**
         * 是否开启swagger
         */
        @Value("${swagger.enabled}")
        private boolean enabled;
    
        /**
         * 设置请求的统一前缀
         */
        @Value("${swagger.pathMapping}")
        private String pathMapping;
    
        /**
         * 分组:sys管理
         *
         * @return Docket
         */
        @Bean
        public Docket sys_api_app() {
            return new Docket(DocumentationType.SWAGGER_2)
                    // 是否启用Swagger
                    .enable(enabled)
                    .apiInfo(apiInfo("标题:学生管理_API", "学生"))
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("cn.springboot.model.web.controller"))
    //                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    // .apis(RequestHandlerSelectors.any())
    //                .paths(PathSelectors.any())
                    .paths(PathSelectors.ant("/stu/**"))
                    .build()
                    .groupName("学生")
                    .securitySchemes(securitySchemes())
                    .securityContexts(securityContexts())
                    .pathMapping(pathMapping);
        }
    
        @Bean
        public Docket clas_api_app() {
            return new Docket(DocumentationType.SWAGGER_2)
                    // 是否启用Swagger
                    .enable(enabled)
                    .apiInfo(apiInfo("标题:班级管理_API", "班级"))
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("cn.springboot.model.web.controller"))
    //                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    // .apis(RequestHandlerSelectors.any())
    //                .paths(PathSelectors.any())
                    .paths(PathSelectors.ant("/class/**"))
                    .build()
                    .groupName("班级")
                    .securitySchemes(securitySchemes())
                    .securityContexts(securityContexts())
                    .pathMapping(pathMapping);
        }
    
        /**
         * 安全模式,这里指定token通过Authorization头请求头传递
         */
        private List<SecurityScheme> securitySchemes() {
            List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
            apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
            return apiKeyList;
        }
    
        /**
         * 安全上下文
         */
        private List<SecurityContext> securityContexts() {
            List<SecurityContext> securityContexts = new ArrayList<>();
            securityContexts.add(
                    SecurityContext.builder()
                            .securityReferences(defaultAuth())
                            .forPaths(o -> o.matches("/.*"))
                            .build());
            return securityContexts;
        }
    
        /**
         * 默认的安全上引用
         */
        private List<SecurityReference> defaultAuth() {
            AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
            AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
            authorizationScopes[0] = authorizationScope;
            List<SecurityReference> securityReferences = new ArrayList<>();
            securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
            return securityReferences;
        }
    
        /**
         * 构建api文档的详细信息
         *
         * @param title       标题
         * @param description 描述
         * @return ApiInfo
         */
        private ApiInfo apiInfo(String title, String description) {
            return new ApiInfoBuilder()
                    .title(title)
                    .description(description)
                    // 作者信息
                    .contact(new Contact(modelConfig.getName(), null, null))
                    .version("版本号:" + modelConfig.getVersion())
                    .build();
        }
    
    //    @Override
    //    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //        registry.addResourceHandler("swagger-ui.html")
    //                .addResourceLocations("classpath:/META-INF/resources/");
    //        registry.addResourceHandler("/webjars/**")
    //                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    //        registry.addResourceHandler("/static/**")
    //                .addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");
    //        WebMvcConfigurer.super.addResourceHandlers(registry);
    //    }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155

    在这里插入图片描述

  • 相关阅读:
    Armv8-R系列之何为MPU?
    ClickHouse教程 — 第二章 ClickHouse快速入门
    LVS-DR
    爬虫 - CSS表达式
    Linux驱动应用层与内核层之间的数据传递
    【MySQL】数据库基础
    直播是未来互联网创业者必备的素质之一?
    如何使用STL中的模板类
    AI图像渲染
    <学习笔记>从零开始自学Python-之-web应用框架Django(一)从Hello World 到 MTV
  • 原文地址:https://blog.csdn.net/qq_42476834/article/details/125534198