怀夢
2021-05-20 10:41
采纳率: 70%
浏览 289
已采纳

idea用spring boot框架引用Swagger报错这个...而且一直不能访问swagger

ERROR  Unable to scan documentation context default
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class springfox.documentation.spi.service.contexts.SecurityContext (java.util.ArrayList is in module java.base of loader 'bootstrap'; springfox.documentation.spi.service.contexts.SecurityContext is in unnamed module of loader 'app')
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2214)
    at com.google.common.cache.LocalCache.get(LocalCache.java:4053)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:4057)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4986)
    at com.google.common.cache.LocalCache$LocalLoadingCache.getUnchecked(LocalCache.java:4992)
    at springfox.documentation.spring.web.scanners.CachingOperationReader.read(CachingOperationReader.java:57)
    at springfox.documentation.spring.web.scanners.ApiDescriptionReader.read(ApiDescriptionReader.java:70)
    at springfox.documentation.spring.web.scanners.ApiListingScanner.scan(ApiListingScanner.java:134)
    at springfox.documentation.spring.web.scanners.ApiDocumentationScanner.scan(ApiDocumentationScanner.java:71)
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.scanDocumentation(DocumentationPluginsBootstrapper.java:101)
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:167)
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178)
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54)
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155)
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:144)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:774)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:439)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:339)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1340)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1329)
    at com.example.emos.wx.EmosWxApiApplication.main(EmosWxApiApplication.java:16)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class springfox.documentation.spi.service.contexts.SecurityContext (java.util.ArrayList is in module java.base of loader 'bootstrap'; springfox.documentation.spi.service.contexts.SecurityContext is in unnamed module of loader 'app')
    at springfox.documentation.spi.service.contexts.OperationContext$1.apply(OperationContext.java:94)
    at com.google.common.collect.Iterators$6.computeNext(Iterators.java:617)
    at com.google.common.collect.AbstractIterator.tryToComputeNext(AbstractIterator.java:145)
    at com.google.common.collect.AbstractIterator.hasNext(AbstractIterator.java:140)
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:249)
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:209)
    at com.google.common.collect.FluentIterable.toList(FluentIterable.java:614)
    at springfox.documentation.spi.service.contexts.OperationContext.securityContext(OperationContext.java:90)
    at springfox.documentation.swagger.readers.operation.OperationAuthReader.apply(OperationAuthReader.java:58)
    at springfox.documentation.spring.web.plugins.DocumentationPluginsManager.operation(DocumentationPluginsManager.java:120)
    at springfox.documentation.spring.web.readers.operation.ApiOperationReader.read(ApiOperationReader.java:73)
    at springfox.documentation.spring.web.scanners.CachingOperationReader$1.load(CachingOperationReader.java:50)
    at springfox.documentation.spring.web.scanners.CachingOperationReader$1.load(CachingOperationReader.java:48)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3628)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2336)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2295)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2208)
    ... 31 common frames omitted

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • 怀夢 2021-05-20 12:20
    已采纳
    package com.example.emos.wx.config;
    
    import io.swagger.annotations.ApiOperation;
    import org.springframework.context.annotation.Bean;
    
    import org.springframework.context.annotation.Configuration;
    
    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.AuthorizationScope;
    import springfox.documentation.service.SecurityReference;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
        @Bean
        public Docket createRestApi(){
            Docket docket=new Docket(DocumentationType.SWAGGER_2);
            //配置Docket基本信息
            ApiInfoBuilder builder=new ApiInfoBuilder();
            builder.title("EMOS在线办公");
            ApiInfo info=builder.build();
            docket.apiInfo(info);
    
            //哪些类的哪些方法要添加到swagger里面
            ApiSelectorBuilder selectorBuilder=docket.select();
            selectorBuilder.paths(PathSelectors.any());
            selectorBuilder.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class));
            selectorBuilder.build();
            ApiKey apikey=new ApiKey("token","token","header");
    
            List<ApiKey> list=new ArrayList<>();
            list.add(apikey);
            docket.securitySchemes(list);
            //设定令牌作用域
            AuthorizationScope scope=new AuthorizationScope("global","accessEverything");
            AuthorizationScope[] scopes={scope};
            SecurityReference reference=new SecurityReference("token",scopes);
            List refList=new ArrayList();
            refList.add(reference);
            SecurityContext context=SecurityContext.builder().securityReferences(refList).build();
            List ctxList=new ArrayList();
            ctxList.add(ctxList);
            docket.securityContexts(ctxList);
            return docket;
        }
    }
    
    

    上面是swagger的配置类,下面是主启动类,卡我好几天了奇怪的很

    package com.example.emos.wx;
    
    
    
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.web.servlet.ServletComponentScan;
    
    
    @ServletComponentScan
    @SpringBootApplication
    public class EmosWxApiApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(EmosWxApiApplication.class, args);
        }
    
    }
    
    已采纳该答案
    打赏 评论
  • 小P聊技术 2021-05-20 10:49

    maven配置pom.xml

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
        
    <properties>
        <springfox-swagger2-version>2.9.2</springfox-swagger2-version>
    </properties>
    
    <dependencies>
    	<!--swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${springfox-swagger2-version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${springfox-swagger2-version}</version>
        </dependency>
    </dependencies>
    

    Swagger2Config.java

    package zzq.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Contact;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    /**
     * 〈功能简述〉<br>
     * 〈swaggerConfig〉
     *
     * @author zhouzhiqiang
     * @create 2018-12-04
     */
    @Configuration
    @EnableSwagger2
    public class Swagger2Config {
        /**
         * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
         *
         * @return Docket
         */
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                    // 为当前包路径
                    .apis(RequestHandlerSelectors.basePackage("zzq.controller")).paths(PathSelectors.any())
                    .build();
        }
    
        /**
         * api文档的详细信息函数,注意这里的注解引用的是哪个
         *
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    // //大标题
                    .title("Admin RESTful API")
                    // 版本号
                    .version("0.0.1-SNAPSHOT")
                    // 描述
                    .description("API 描述")
                    //作者
                    .contact(new Contact("zhouzhiqiang", "https://blog.csdn.net/qq_33594101", "2044579211@qq.com"))
                    .build();
        }
    }
    

    访问路径

    http://localhost:8080/swagger-ui.html#/

    打赏 评论
  • 小P聊技术 2021-05-20 10:50

    直接这样看,好像看不到问题,你要把配置的代码发出来,看下,应该是配置有问题

    打赏 评论
  • 小P聊技术 2021-05-20 15:32
    package com.ts.core.common.utils;
    
    import com.github.xiaoymin.swaggerbootstrapui.model.OrderExtensions;
    import com.google.common.collect.Lists;
    import io.swagger.annotations.ApiOperation;
    import org.springframework.stereotype.Component;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.ParameterBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.*;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.Docket;
    
    import java.util.List;
    
    import static com.google.common.collect.Lists.newArrayList;
    
    /**
     * 类文件: SwaggerUtil
     * <p>
     * <p>
     * 类描述:
     * <p>
     * 作     者: AusKa_T
     * <p>
     * 日     期: 2021/4/21 0021
     * <p>
     * 时     间: 10:43
     * <p>
     */
    @Component
    public class SwaggerUtil {
    
        /**
         * 创建API
         *
         * @param groupName   分组名称
         * @param basePackage 扫描的包路径
         * @param title       标题
         * @param description 描述
         * @return 结果
         */
        public Docket createRestApi(String groupName, String basePackage, String title, String description) {
            ParameterBuilder parameterBuilder = new ParameterBuilder();
            List<Parameter> parameters = Lists.newArrayList();
            parameterBuilder
                    .name("token")
                    .description("token令牌")
                    .modelRef(new ModelRef("String"))
                    .parameterType("header")
                    .defaultValue("Bearer")
                    .required(false).build();
            parameters.add(parameterBuilder.build());
    
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo(title, description))
                    .groupName(groupName)
                    .select()
                    //加了ApiOperation注解的类,才生成接口文档
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    //包下的类,才生成接口文档
                    .apis(RequestHandlerSelectors.basePackage(basePackage))
    //                .paths(PathSelectors.any())
                    .build()
                    .extensions(Lists.newArrayList(new OrderExtensions(1)))
                    .globalOperationParameters(parameters)
                    .securityContexts(Lists.newArrayList(securityContext()))
                    .securitySchemes(security());
        }
    
        /**
         * 构建API info
         *
         * @param title 标题
         * @return 结果
         */
        private ApiInfo apiInfo(String title, String description) {
            return new ApiInfoBuilder()
                    .title(title)
                    .description(description)
                    .termsOfServiceUrl("https://www.test.com")
                    .version("1.0.0")
                    .build();
        }
    
        /**
         * 设置验证规则
         *
         * @return 结果
         */
        private List<ApiKey> security() {
            return newArrayList(
                    new ApiKey("token", "token", "header")
            );
        }
    
        /**
         * 设置数据验证规则
         *
         * @return 结果
         */
        private SecurityContext securityContext() {
            return SecurityContext.builder()
                    .securityReferences(defaultAuth())
                    .forPaths(PathSelectors.regex("/.*"))
                    .build();
        }
    
        /**
         * 设置默认验证方式
         *
         * @return 结果
         */
        List<SecurityReference> defaultAuth() {
            AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
            AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
            authorizationScopes[0] = authorizationScope;
            return Lists.newArrayList(new SecurityReference("token", authorizationScopes));
        }
    
    
    }
    
    package com.ts.society.config;
    
    import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
    import com.ts.core.common.utils.SwaggerUtil;
    import com.ts.society.common.constants.SysConstants;
    import com.ts.society.common.enums.Modules;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import javax.annotation.Resource;
    
    /**
     * 类文件: SwaggerConfig
     * <p>
     * <p>
     * 类描述:Swagger配置
     * <p>
     * 作     者: AusKa_T
     * <p>
     * 日     期: 2021/5/7 0007
     * <p>
     * 时     间: 14:13
     * <p>
     */
    @Profile({"dev","test"})
    @Configuration
    @EnableSwagger2
    @EnableSwaggerBootstrapUI
    public class SwaggerConfig implements WebMvcConfigurer {
    
        /**
         * swagger工具类
         */
        @Resource
        private SwaggerUtil swaggerUtil;
    
        /**
         * 系统设置
         * @return 结果
         */
        @Bean
        public Docket createRestSysApi() {
            return swaggerUtil.createRestApi("系统设置","com.demo.modules.sys",""系统设置"", ""系统设置"");
        }
    
    
    
    
    
    }
    
    打赏 评论

相关推荐 更多相似问题