【问题标题】:Springfox swagger 2 not working with Spring Boot 1.5: HTTP 404 not found at /v2/api-docsSpringfox swagger 2 不适用于 Spring Boot 1.5:在 /v2/api-docs 中找不到 HTTP 404
【发布时间】:2019-11-12 02:41:43
【问题描述】:

我有一个 Spring Boot 项目,其中 springfox-swagger-2 作为依赖项。

使用的版本:

  • Spring Boot:1.5.9.RELEASE
  • springfox-swagger-2:2.7.0

这是配置:

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

            api.apiInfo(apiInfo())
                .globalOperationParameters(Lists.newArrayList(new ParameterBuilder()
                .name("Example api info")
                .description("description")
                .modelRef(new ModelRef("string"))
                .parameterType("parameter type example").build()))
            ;
        return api;
    }

    @SuppressWarnings("rawtypes")
    private ApiInfo apiInfo() {
        Contact contact = new Contact("name", "url", "email");
        Collection<VendorExtension> vendorExtensions = new ArrayList<>();
        return new ApiInfo("title", "description", "version", "termsOfServiceUrl", contact, "license", "licenseUrl", vendorExtensions);
    }
}

应用程序正确启动,但 url /v2/api-docs 得到 HTTP 404 Not Found

即使 /swagger-ui.html 也不可用,添加 springfox-swagger-ui 的依赖项

引导日志没有报告任何错误。

我已经尝试找到其他类似问题的答案,但其中任何一个都有效!

任何帮助将不胜感激。

【问题讨论】:

  • springfox-swagger-ui 依赖添加了吗?
  • 当然版本和springfox-swagger-2一样
  • 你好 @AlessandroC 你使用的是 Spring Security,如果是,你可能需要为其添加配置
  • @Patel Romil 嗨,是的,我有 Spring Security,而且我已经有了它的配置!
  • 你好@AlessandroC 请看一个适合我的答案

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


【解决方案1】:

SwaggerConfig.java

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 apiDocket() {

       Docket docket =  new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.."))
                .paths(PathSelectors.any())
                .build();

       return docket;

    } 
}

SecurityConfig.java

public class SecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer{

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

    @Override
        protected void configure(HttpSecurity http) throws Exception{

             http
             .csrf().disable()
             .authorizeRequests()
             .antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**")
             .permitAll()
             .anyRequest().authenticated();
        }

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

pom.xml

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

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

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

【讨论】:

  • 试过了,但它对我的项目不起作用...此外,我刚刚尝试禁用 application.properties 上的安全性,即使在 Spring 安全性关闭的情况下它也不起作用,所以这不是与 Spring Security 相关的问题。
【解决方案2】:

尝试将此添加到 yourapplication.properties

spring.resources.add-mappings=true

【讨论】:

    【解决方案3】:

    我终于找到了让它工作的方法。

    springfox-swagger-2 实现在 springfox.documentation.swagger2.web.Swagger2Controller 类中有一个 @Controller

    这个类用这个方法实现了url"/v2/api-docs"的映射:

    @RequestMapping(
        value = DEFAULT_URL,
        method = RequestMethod.GET,
        produces = { APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE })
    @PropertySourcedMapping(
        value = "${springfox.documentation.swagger.v2.path}",
        propertyKey = "springfox.documentation.swagger.v2.path")
    @ResponseBody
    public ResponseEntity<Json> getDocumentation(
        @RequestParam(value = "group", required = false) String swaggerGroup,
        HttpServletRequest servletRequest) {
    
      String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
      Documentation documentation = documentationCache.documentationByGroup(groupName);
      if (documentation == null) {
        return new ResponseEntity<Json>(HttpStatus.NOT_FOUND);
      }
      Swagger swagger = mapper.mapDocumentation(documentation);
      UriComponents uriComponents = componentsFrom(servletRequest, swagger.getBasePath());
      swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
      if (isNullOrEmpty(swagger.getHost())) {
        swagger.host(hostName(uriComponents));
      }
      return new ResponseEntity<Json>(jsonSerializer.toJson(swagger), HttpStatus.OK);
    }
    

    如您所见,RequestMapping 需要一个名为"group" 的参数。 因此,如果您在没有"group" 参数的情况下调用"/v2/api-docs" url,则获得的文档为空,因为缓存中没有键""(空字符串)的文档。

    我解决了添加以这种方式实现的自定义过滤器:

    @Component
    public class SwaggerFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
    
            String group = req.getParameter("group");
    
            if (req.getServletPath().equals("/v2/api-docs") && group==null) {
                res.sendRedirect("api-docs?group=default");
            } else {
                chain.doFilter(request, response);
            }
    
        }
    
        @Override
        public void destroy() {
    
        }
    
    }
    

    机制很简单:没有"group" 参数,有"default" 组参数的重定向。

    【讨论】:

      【解决方案4】:

      在将 Spring Boot 从 2.0.4.RELEASE 版本迁移到 2.1.6.RELEASE 版本时,我还偶然发现了 /v2/api-docsHTTP 404 Not Found(但在单元测试期间) .单元测试在“升级”之前通过。

      单元测试类有以下注解:

      @Category(UnitIntegrationTest.class)
      @RunWith(SpringRunner.class)
      @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
      @ContextConfiguration(classes = {SecurityConfiguration.class})
      @ActiveProfiles("test")
      

      并且测试配置被定义为一个内部类:

      @Configuration
      @EnableWebMvc
      @EnableSwagger2
      @Import(value = BeanValidatorPluginsConfiguration.class)
      public static class TestSwaggerConfiguration {
      
          @Bean
          public Docket api() {
              return new Docket(DocumentationType.SWAGGER_2)
                  .select()
                  .apis(RequestHandlerSelectors.basePackage("the.package.we.want"))
                  .paths(PathSelectors.any())
                  .build();
          }
      }
      

      解决方法是在@ContextConfiguration 中指定TestSwaggerConfiguration,例如:

      @Category(UnitIntegrationTest.class)
      @RunWith(SpringRunner.class)
      @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
      @ContextConfiguration(classes = {SecurityConfiguration.class, GenerateDocumentationTest.TestSwaggerConfiguration.class})
      @ActiveProfiles("test")
      

      附带说明,在点击 HTTP 404 之前,我还必须指定

      spring.main.allow-bean-definition-overriding=true
      

      application-test.properties 中,根据Spring Boot 2.1 Release Notes

      【讨论】:

        【解决方案5】:

        如果卡住的人是像我这样的菜鸟,请确保在 pom.xml 文件中添加依赖项后运行 Maven Install 命令。 p>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-01-22
          • 2022-01-07
          • 2020-02-25
          • 2019-06-08
          • 1970-01-01
          • 2015-07-22
          • 2020-06-11
          相关资源
          最近更新 更多