添加了Springfox Swagger-UI并且它无法正常工作,我缺少什么?

时间:2017-09-11 08:45:36

标签: spring spring-boot swagger swagger-ui springfox

按照此处的说明操作:

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返回:

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

我错过了什么?

15 个答案:

答案 0 :(得分:12)

我尝试了大多数这些答案,最终的解决方案令人毛骨悚然。

正确的网址如下

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

我正在使用Springfox swagger-ui 3.x.x

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

答案 1 :(得分:4)

  

我遇到了这个问题,因为我的端点有请求映射,这些映射有这种形式的路径变量:/ {var}。事实证明这对于GET和POST端点都是一个问题,即GET / {var}和POST / {var}阻止swagger-ui。一旦我把路径变得更加具体,我就会兴高采烈地工作。

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

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

通过调查评论中的各种想法找到。

答案 2 :(得分:3)

对于Spring Version> = 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链接: http:// localhost:8080 / swagger-ui / index.html#/

答案 3 :(得分:2)

已经有很多答案说明了正确的方法,但是仍然有一些关于错误的困惑。

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

现在,只需要在pom.xml中添加一个依赖项即可。

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

启动应用程序后,您可以通过点击两个新的招摇网址来获取文档

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

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

答案 4 :(得分:1)

我也遇到了这个问题,问题是我们有一个没有路径映射的控制器(因此映射到“ /”)。那阻止了对swagger-ui资源的请求。

答案 5 :(得分:1)

注意:springfox版本3.0.0抛出带有以下解决方案的Whitelabel错误页面

Spring boot 2.3.3发布

即使这样,请求映射是否具有路径变量也没关系。

经过许多解决方案页面后,没有任何效果。但是

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

运行( 绝对需要 ):Mvn clean

@Configuration
@EnableSwagger2

无需添加新的Docket Bean即可进行简单的灵活配置(即路径和基本包)

答案 6 :(得分:0)

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

答案 7 :(得分:0)

在控制器级别添加@RequestMapping("/"),它可以工作。

答案 8 :(得分:0)

结论:我发现在maven存储库${user_home}/.m2/repository/io/springfox/springfox-swagger-ui/2.9.2下没有jar文件,执行以下步骤后一切正常。

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

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

我的spring boot版本是2.2.2。

答案 9 :(得分:0)

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

我能够解决此问题

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

答案 10 :(得分:0)

如果您使用的是Spring Boot版本> = 2.2,则建议使用SpringFox Swagger版本3.0.0。保持您的pom.xml依赖项配置如下:

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

保留如下所示的Swagger配置类:

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

答案 11 :(得分:0)

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

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

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

  • 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

答案 12 :(得分:0)

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 类

@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 类(确保没有使用 @EnableWebMvc 注释,否则你会遇到错误)

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

安全配置类

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

答案 13 :(得分:0)

如果您使用 版本 - 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 浏览器网址 -> http://localhost:8080/swagger-ui/#/ 运行(必须):Mvn clean

答案 14 :(得分:0)

我试图在一个单个文件中将 Swagger @Configuration 类与 @EnableWebMvc 类结合起来。

不工作:

@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 类中制作它,例如在文档中:

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

}