簡體   English   中英

Spring Boot Swagger API 不起作用

[英]Spring Boot Swagger API not working

這是我的pom.xml

<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>

我正在使用 Spring Boot 的1.5.3.RELEASE版本。 這是我的招搖配置文件:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket swagger() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}

這是我的WebSecurityConfig.java

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources", "/configuration/security", "/swagger-ui.html", "/webjars/**");
}

當我從端點http://localhost:8080/v2/api-docs獲取數據時,我會返回 JSON:

{
  "swagger": "2.0",
  "info": {
    "description": "Api Documentation",
    "version": "1.0",
    "title": "Api Documentation",
    "termsOfService": "urn:tos",
    "contact": {},
    "license": {
      "name": "Apache 2.0",
      "url": "http://www.apache.org/licenses/LICENSE-2.0"
    }
  },
  "host": "localhost:8080",
  "basePath": "/",
  //ETC
}

但是當我嘗試訪問localhost:8080/swagger-ui.html的 UI 時,我得到一個如下所示的空白頁面: 在此處輸入圖片說明

如果我點擊頁面,我會得到提升在此處輸入圖片說明

我究竟做錯了什么? 這是某種彈簧安全問題嗎?

您可以在應用程序配置中使用springfox.documentation.swagger.v2.path屬性向 Swagger 建議 API 描述路徑,例如springfox.documentation.swagger.v2.path: /rest/docs in application.yml

在 github 上發布了一個例子。

很可能 spring-security 不允許/阻止您的端點被發現。 嘗試將您的螞蟻匹配器更改為以下內容,看看是否有幫助。 安全/ui 配置端點不正確。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(
        "/v2/api-docs", 
        "/swagger-resources/configuration/ui",     
        "/swagger-resources", 
        "/swagger-resources/configuration/security", 
        "/swagger-ui.html",     
        "/webjars/**");
}

將 swagger 版本更改為 2.9.2 它將起作用。

   <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <version>2.9.2</version>
   </dependency>

如果您使用版本 - V3 || io.springfox >= 3.0.0

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-boot-starter</artifactId>
   <version>3.0.0</version>
</dependency>

Java代碼

@Configuration
@EnableSwagger2

public class SwaggerConfig {

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2).select()
            .apis(RequestHandlerSelectors.basePackage("Your Controller package name"))
            .paths(PathSelectors.any()).build();
}

}

V3 瀏覽器 URL -> http://localhost:8080/swagger-ui/#/運行(必備):Mvn clean

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM