Springfox swagger 2不适用于Spring Boot 1.5:在/ v2 / api-docs中找不到HTTP 404

时间:2019-07-01 12:27:04

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

我有一个以springfox-swagger-2作为依赖项的Spring Boot项目。

使用的版本:

  • 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

即使/swagger-ui.html也无法添加springfox-swagger-ui的依赖项

引导程序日志未报告任何错误。

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

任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:0)

尝试将其添加到yourapplication.properties

spring.resources.add-mappings=true

答案 1 :(得分:0)

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>

答案 2 :(得分:0)

最后,我找到了使其工作的方法。

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

此类通过以下方法为网址"/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"的参数。 因此,如果您在没有"/v2/api-docs"参数的情况下调用"group"网址,则获得的文档为null,因为高速缓存中没有键""(空字符串)的文档。

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

@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"组参数的重定向。

答案 3 :(得分:0)

我还偶然发现/v2/api-docs HTTP 404 未找到(但在单元测试中),这是将Spring Boot从2.0.4.RELEASE迁移到2.1.6的一部分。 。发布。单元测试在“升级”之前通过。

单元测试类具有以下注释:

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

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

@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
根据{{​​3}}在application-test.properties

答案 4 :(得分:0)

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