为什么springfox-swagger2 UI告诉我"无法推断基本网址".

dja*_*fan 23 swagger-ui swagger-2.0

为什么springfox-swagger2 UI告诉我Unable to infer base url. 据我所知,我使用的是典型的Swagger spring-boot配置.

正如您在屏幕截图中看到的那样,支持UI的swagger-fox网址是example.com/api.注意:Whitelabel Error Page 当我导航到https:// localhost:9600/api/v2/api-docs /时, 我得到一个标准的Spring .我怀疑这是问题的根源?我没有看到Spring没有加载的错误,springfox-swagger2所以我不知道为什么这不起作用.

在此输入图像描述

我的配置看起来像这样(我已尝试过此配置的各种变体,从网上搜索建议):

@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = {"com.company.project"})
public class SwaggerConfig
{
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.cloud")))
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.data.rest.webmvc")))
                .paths(PathSelectors.any())
                .build();
    }
}
Run Code Online (Sandbox Code Playgroud)

<!-- to generate /swagger-ui.html -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

注意:有趣的是,当我尝试2.6.0版时,我没有获得模态弹出窗口,但我的Swagger UI显示0 api内容.所以,我知道模态必须是相当新的?

如果这里没有足够的信息,请给我留言.

Shi*_*ari 23

通过添加带注释的SpringBootApplication,我能够解决这个问题 - 正如Mark所建议的那样:

@EnableSwagger2
Run Code Online (Sandbox Code Playgroud)

  • 这仍然适用于 springfox swagger 3.0.0 吗?我有完全相同的问题,这个修复没有做任何事情。 (3认同)

Nor*_*oor 12

对我来说问题是Spring Security不允许访问swagger-ui所需的一些资源.解决方案是允许匿名访问以下路径:

  • /swagger-ui.html
  • / webjars/**
  • / V2/**
  • /招摇资源/**

在我的情况下,没有身份验证就可以访问这些资源.


小智 6

@EnableSwagger2在Springboot应用程序的主文件中添加注解

@SpringBootApplication
@EnableSwagger2
public class SampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SampleApplication.class, args);
    }

}
Run Code Online (Sandbox Code Playgroud)


dja*_*fan 5

事实证明,解决我的问题的方法是将@EnableSwagger2 注释与Docket Bean一起移入主Configuration类。

我已经在Docket Bean的子包中创建了一个单独的类,我期望它会被Spring扫描并加载Bean。也许我无法使用来注释该类@Component,或者问题出在别的东西上,但是我使它起作用了。


Sob*_*han 5

就我而言,我的WebSecurityConfig.java中有这一行:

.antMatchers("swagger-ui.html").permitAll()
Run Code Online (Sandbox Code Playgroud)

当我添加这个时:

.antMatchers("/swagger-resources/**").permitAll()
Run Code Online (Sandbox Code Playgroud)

我的问题解决了。