配置 Swagger 以忽略 Spring Boot Actuator 端点

Configuring Swagger to ignore Spring Boot Actuator endpoints

Spring 在此处启动 RESTful Web 服务和 Swagger 2。我有以下 @Configuration class 设置来为我的服务配置 Swagger:

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

我开始我的服务,然后转到 http://localhost:8080/v2/api-docs(Swagger 的服务来源),然后将 JSON 粘贴到 jsonlint.com 中,然后我看到 Spring Boot 会自动添加大约 40 个端点,我 不想 Swagger 记录这些端点。 /trace 端点、/health/env/beans 等。这些都是 Spring Boot Actuator 创建但我不想要的东西包含在我的 public API 文档中。

有没有办法将 Swagger 配置为记录这些框架级端点?

使用 any() 将使整个 API 的文档通过 Swagger 可用。使用 PathSelectors.ant() 来限制您的端点。 像

.paths(PathSelectors.ant("/finance/**")) 只会显示 /finance/

下的端点
RequestHandlerSelectors.any()

将公开您项目的所有端点。

除了上述答案之外,您还可以通过在 RequestHandlerSelectors.basePackage()[=17= 中提供您的基本包名称来添加使用以下代码来限制 API 的曝光]方法。

@Bean
public Docket api() { 
    return new Docket(DocumentationType.SWAGGER_2)  
      .select()                                  
      .apis(RequestHandlerSelectors.basePackage("com.assingment.scalableweb"))
      .paths(PathSelectors.any())                          
      .build()
      .apiInfo(metaData())
      .tags(new Tag("DifferenceController", "Operations related to the Json Data")); 
}