使用swagger时出现Unable to infer base url. This is common when using dynamic servlet registra

发布时间 2023-08-13 17:05:07作者: 哩个啷个波

在使用Swagger的时候访问地址后出现了错误,http://localhost:8001/swagger-ui.html

一直在弹窗提示,还取消不了

image-20230813164309945

我这边自己的问题可能是因为Swagger类没有跟启动类在同一个模块当中,虽然我将Swagger所在的模块进入到启动类所在的模块,但是可能是idea没有识别到.还是报错,可以按照以下步骤检查一下是不是出现了问题,

出现以上错误提示的原因是没有启用swagger2,也就是没有使用@EnableSwagger2,很多文章中说在启动类加上@EnableSwagger2即可,虽然添加后能够正常访问http://localhost:8080/swagger-ui.html页面,但是并不能识别到添加swagger相关注解的controller,正确的使用方式是,添加swagger配置类并指定扫描路径:

package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author bab
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig{
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 指定路径
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("没有说明")
                .version("1.0.0")
                .build();
    }
}

注解添加完了

注意:如果配置类所属的包不是启动类的同级或子级则需要在启动类上自己指定需要扫描对应路径,例如:@ComponentScan("com.example.demo.config")

我就是属于这种情况,首先是看下pom.xml文件中是不是引入了Swagger所在的包,所在的模块,然后接着就是在当前模块启动类上面添加@ComponentScan("com.example.demo.config") 注意这里面写的最好和当前所在模块包路径名称保持一致,否则可能会把当前类所在的包路径给覆盖掉,默认是扫描该类所在的包和子包的,看这里https://www.cnblogs.com/javaxubo/p/17626635.html

image-20230813165257478

其他地方就没有了.可以重启一下idea,或者把target给删除掉,rebuild一下项目等操作.重启看看.我到这里就好使了.