添加了 Springfox Swagger-UI 但它不起作用,我错过了什么?

Added Springfox Swagger-UI and it's not working, what am I missing?

按照此处的说明进行操作:

http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

我将这些依赖项添加到我的项目中:

compile "io.springfox:springfox-swagger2:2.7.0"
compile "io.springfox:springfox-swagger-ui:2.7.0"

并像这样配置 SpringFox Swagger:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

但是 Swagger UI 似乎没有启用。我试过了:

我得到的是:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Mon Sep 11 09:43:46 BST 2017
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported

我在日志中看到:

2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] o.s.web.servlet.PageNotFound             : Request method 'GET' not supported
2017-09-11 09:54:31.020  WARN 15688 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

http://localhost:8080/swagger-resources returns:

[{"name": "default",
  "location": "/v2/api-docs",
  "swaggerVersion": "2.0"}]

我错过了什么?

I ran into this issue because I had endpoints with request mappings that had path variables of this form: /{var}. Turns out that this is an issue for both GET and POST endpoints i.e. GET /{var} and POST /{var} block swagger-ui. Once I made the paths more specific, I got swagger-ui to work.

引自https://github.com/springfox/springfox/issues/1672

当 spring 找到只有一个变量的简单路径时,swagger 无法拦截 URL。

通过调查评论中的各种想法发现。

我也 运行 参与其中,问题是我们的控制器没有路径映射(因此映射到“/”)。那阻止了对 swagger-ui 资源的请求。

在控制器级别添加 @RequestMapping("/")(在 @RestController\@Controller 注释之后)帮助我摆脱了 Request method 'GET' not supported 问题。 Thanks to Dhermanns's suggestion

在控制器级别添加@RequestMapping("/"),有效。

结论:我发现maven库下没有jar文件${user_home}/.m2/repository/io/springfox/springfox-swagger-ui/2.9.2,按照下面的步骤一切正常。

我通过以下步骤解决了这个问题:

  • 转到${user_home}/.m2/repository/io/springfox/springfox-swagger-ui/2.9.2
  • 检查2.9.2下的文件是否完整。如果有文件丢失,请删除整个2.9.2目录
  • 在intellij idea中执行reimport all maven projects

我的spring引导版本是2.2.2。

我遇到了 swagger 问题 /swagger-ui.html 请求方法 'get' 不是 supported\request 方法 'get' 不受支持。\支持的方法 post

我能够解决问题

在我的控制器中 api @RequestMapping() 没有路径信息。提供如下路径 Fix - @RequestMapping(value = '/v1/createAnalytic')

我尝试了其中的大部分答案,但最终的解决方案令人毛骨悚然..

右边URL是下面的

http://localhost:8080/swagger-ui/

我正在使用 Springfox swagger-ui3.x.x

参考完整的 swagger 设置: http://muralitechblog.com/swagger-rest-api-dcoumentation-for-spring-boot/

如果您使用的是Spring Boot Version >= 2.2,我推荐使用SpringFox Swagger version 3.0.0。保持你的 pom.xml 依赖配置如下:

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

保持您的 Swagger 配置 class 如下所示:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

public static final Contact DEFAULT_CONTACT = new Contact(
        "Sample App", "http://www.sample.com", "sample@gmail.com");

public static final ApiInfo DEFAULT_API_INFO = new ApiInfo(
        "Awesome API Title", "Awesome API Description", "1.0",
        "urn:tos", DEFAULT_CONTACT,
        "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", Arrays.asList());

private static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES =
        new HashSet<String>(Arrays.asList("application/json",
                "application/xml"));

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(DEFAULT_API_INFO)
            .produces(DEFAULT_PRODUCES_AND_CONSUMES)
            .consumes(DEFAULT_PRODUCES_AND_CONSUMES);
 }
}

现在,通过访问此 URL 访问您的 swagger UI:http://localhost:8080/swagger-ui/index.html#/

对于Spring版本>=2.2,你应该添加依赖springfox-boot-starter

pom.xml:

<properties>
    <java.version>1.8</java.version>
    <io.springfox.version>3.0.0</io.springfox.version>
</properties>

<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>${io.springfox.version}</version>
    </dependency>
</dependencies>

ApplicationSwaggerConfig

@Configuration
@EnableSwagger2
public class ApplicationSwaggerConfig {

    @Bean
    public Docket employeeApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

}

Swagger-UI link: http://localhost:8080/swagger-ui/index.html#/

Springfox 3.0.0 only works with Spring Boot <= 2.6.0-M2 but not with versions above it


1. spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER #-> App.properties
    -    But without Actuator
2. @EnableWebMvc
3. Migrate to springdoc-openapi-ui - same steps as io.springfox >= 3.X

io.springfox >= 2.X

io.springfox >= 3.X

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-schema</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
browser URL
http://localhost:8080/swagger-ui.html
browser URL
http://localhost:8080/swagger-ui/
http://localhost:8080/swagger-ui/index.html
Must Need

mvn clean

Must Need

mvn clean

@Configuration
@EnableSwagger2
@Configuration
@EnableSwagger2

已经有很多答案给出了正确答案,但仍然存在一些关于错误的混淆。

如果您使用的是Spring Boot Version >= 2.2,建议使用SpringFox Swagger version 3.0.0

现在,只需要在 pom.xml.

中添加一个依赖项 uired
<!-- Swagger dependency -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

应用程序启动后,您可以通过点击任一新的 swagger URL 来获取文档

选项 1: http://localhost:8080/swagger-ui/

选项 2: http://localhost:8080/swagger-ui/index.html

对于版本 3.0.0 只有一个依赖项:

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

之后您可以访问 swagger-ui on:

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

版本 2.x.x

<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${io.springfox.version}</version>
</dependency>
<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${io.springfox.version}</version>
</dependency>

访问 swagger-ui 于:http://localhost:8080/swagger-ui

io.springfox >= 3,并且还使用 SpringSecurity

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>

SpringFoxConfig Class

@Configuration
@EnableSwagger2
public class SpringFoxConfig implements WebMvcConfigurer {
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .apiInfo(getApiInfo());
}

private ApiInfo getApiInfo() {
    return new ApiInfo(
            "company_name",
            "message here",
            "VERSION_1",
            "TERMS OF SERVICE URL",
            new Contact("company", "url", "EMAIL"),
            "LICENSE",
            "LICENSE URL",
            Collections.emptyList()
      );
     }
   }

WebConfig Class(确保未使用 @EnableWebMvc 注解,否则会 运行 出错)

   @Configuration
  //@EnableWebMvc
   public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH", 
           "OPTIONS");
        }
      }

安全配置class

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
        // -- Swagger UI v2
        "/v2/api-docs",
        "/swagger-resources",
        "/swagger-resources/**",
        "/configuration/ui",
        "/configuration/**",
        "/configuration/security",
        "/swagger-ui.html",
        "/webjars/**",
        // -- Swagger UI v3 (OpenAPI)
        "/v3/api-docs/**",
        "/swagger-ui/**",
        "/swagger-ui/",
        "/swagger-ui"
        // other public endpoints of your API may be appended to this array

        @Override
protected void configure(HttpSecurity httpSecurity) throws Exception{
    httpSecurity.cors();
    httpSecurity.csrf().disable();
    httpSecurity.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(AUTH_WHITELIST).permitAll()
                .anyRequest()
                .authenticated();

                httpSecurity.addFilterBefore(jwtRequestFilter, 
                             UsernamePasswordAuthenticationFilter.class);
         }
     };

如果您使用 版本 - 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

我试图将 Swagger @Configuration class 与 @EnableWebMvc class 合并到一个 单个 文件中。

不工作:

@Configuration
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfiguration extends WebMvcConfigurerAdapter {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

解决方案 是将其分为 2 个单独的 java classes,就像在文档中一样:

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }
}


@Configuration
@EnableWebMvc
public class WebAppConfig implements WebMvcConfigurer {

    @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/");
    }

}

尝试重新启动您的 IDE。

在尝试了很多这些建议但仍然没有成功之后,我发现了这个博客 post:https://medium.com/swlh/openapi-swagger-ui-codegen-with-spring-boot-1afb1c0a570e

作者指出,“注意:如果您收到 Whitelabel 错误页面,请尝试重新启动您的 IDE 和 运行 项目。”

这很有效。

这条评论节省了我很多时间。简而言之 - 我发现我的项目中有人像这样向控制器添加了映射:

@RestController("/api/test")

当然它应该是这样的:

@RestController
@RequestMapping("/api/test")

由于上述原因,我在尝试查看 swagger-ui 时收到了 405 个回复。

@RestConroller 的文档更准确地解释了这个问题:

The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component. Returns: the suggested component name, if any (or empty String otherwise) Since: 4.0.1

我最近遇到了类似的问题

http://localhost:8080/swagger-ui/ - 没用

http://localhost:8080/swagger-ui/index.html - 工作正常

...最后这个问题是由我的 pom.xml

中的一些混乱引起的
<dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>3.0.0</version>
    </dependency>

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>3.0.0</version>
    </dependency>

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

我删除了前两个依赖,所以只剩下springfox-boot-starter 经过几次 Maven 清理并重新启动应用程序后,第一条路径也开始正常工作 http://localhost:8080/swagger-ui/

如果您想使用 3.0 版,您还必须在 Docket 构造函数中将 DocumentationType 更改为 OAS_30

@Bean
public Docket api() {
  return new Docket(DocumentationType.OAS_30)
                           .select()
                           .apis(RequestHandlerSelectors.any())
                           .paths(PathSelectors.any())
                           .build();
}

对我来说,这是一个问题,因为现有的 API

我在控制器上有一个 Existing API,就像

http://localhost:8080/{PathParam}

我改成了

http://localhost:8080/domain/{PathParam}

问题已解决!!!

Had to do 2 things to fix it:
1) added below dependency and removed other swagger dependencies
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version>
    </dependency>
2) org.springframework.security dependency in pom.xml was blocking the swagger-ui, so added below code to bypass security for swagger ui:
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs",
                                   "/swagger-resources/**",
                                   "/swagger-ui/**");
    }
}