【问题标题】:Added Springfox Swagger-UI and it's not working, what am I missing?添加了 Springfox Swagger-UI 但它不起作用,我错过了什么?
【发布时间】:2018-02-19 10:47:42
【问题描述】:

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

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"}]

我错过了什么?

【问题讨论】:

  • 您是否有任何可以阻止访问的弹簧安全措施?
  • @StanislavL:不,我还没有启用安全性。
  • @StanislavL:我添加了我得到的日志错误,它是一个 PageNotFound。
  • @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).groupName("users-public-api") .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .pathMapping("/") .enableUrlTemplating(false); } 这是我的工作配置。
  • @StanislavL:我试过了,同样的错误。

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


【解决方案1】:

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/
Must Need

mvn clean

Must Need

mvn clean

@Configuration
@EnableSwagger2
@Configuration
@EnableSwagger2

【讨论】:

    【解决方案2】:

    我尝试了这些答案中的大部分,但最终的解决方案正在蔓延..

    正确的网址如下

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

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

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

    【讨论】:

    • 最后的/是非常重要的部分
    • OMFG 这太不可思议了。我整个周末都浪费在这上面。感谢您提供此解决方案。
    • 在 swagger-ui 的 url 末尾添加 / 对我有用。
    • 它对我不起作用。仍然得到 401。基本上,当我尝试输入 localhost:8080 时,它会要求输入用户名和密码,这很奇怪。我只能用邮递员查东西,不能查网址。
    • @HuserB1989 也许启用了 Spring Security。您可以删除依赖项并尝试
    【解决方案3】:

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

    如果您使用的是 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>
    

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

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

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

    【讨论】:

    • 非常感谢。这拯救了我的一天。我输入 URL 为“localhost:8080/swagger-ui”,但无法获取 UI,但最后使用“/”,它呈现得像魔术一样。你能在最后解释一下这个“/”吗?是强制性的吗?
    • 很高兴您发现这很有用。是的,在新版本中,末尾的“/”是强制性的。你也可以参考这个博客:baeldung.com/swagger-2-documentation-for-spring-rest-api
    • 这首先对我不起作用。但经过几次尝试后它起作用了。我不知道为什么。遵循youtube.com/… 上的教程后,我面临同样的问题。其中一个 cmets 使用此方法解决了同样的问题。
    【解决方案4】:

    我遇到了这个问题,因为我有带有请求映射的端点,这些端点具有这种形式的路径变量:/{var}。事实证明,这对于 GET 和 POST 端点(即 GET /{var} 和 POST /{var} 块 swagger-ui)都是一个问题。一旦我使路径更具体,我就可以使用 swagger-ui。

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

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

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

          如果您使用的是 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#/

          【讨论】:

          • 为我工作了 url localhost:8181/&lt;base-path&gt;/swagger-ui/index.html
          【解决方案8】:

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

          【讨论】:

            【解决方案9】:

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

            【讨论】:

            • 我已经完成了所有这些步骤,仍然大摇大摆地显示 404
            【解决方案10】:

            我试图将 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/");
                }
            
            }
            

            【讨论】:

              【解决方案11】:

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

              【讨论】:

                【解决方案12】:

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

                【讨论】:

                  【解决方案13】:

                  结论:我发现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 idea 中执行 reimport all maven projects

                  我的spring boot版本是2.2.2。

                  【讨论】:

                    【解决方案14】:

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

                    我能够解决问题

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

                    【讨论】:

                      【解决方案15】:

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

                      【讨论】:

                        【解决方案16】:

                        尝试重新启动您的 IDE。

                        在尝试了许多这些建议但仍然没有任何运气之后,我看到了这篇博文:https://medium.com/swlh/openapi-swagger-ui-codegen-with-spring-boot-1afb1c0a570e

                        作者所说的“注意:如果您收到 Whitelabel 错误页面,请尝试重新启动您的 IDE 并再次运行该项目。”

                        这就像一个魅力。

                        【讨论】:

                          猜你喜欢
                          • 2022-10-06
                          • 2020-09-14
                          • 1970-01-01
                          • 2016-05-27
                          • 2020-08-26
                          • 2022-01-21
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          相关资源
                          最近更新 更多