我正在开发 Spring Boot 应用程序,我使用 Swagger 作为文档。
我已经在我的应用程序中添加了 Spring Boot Actuator,但现在我想在我的 swagger 文档中添加由执行器 (/health /metrics ..) 创建的新服务。
我没有找到如何配置Actuator和Swagger。
您可以在 Swagger 中配置要将哪些路径添加到文档中:
@Bean
public Docket appApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
...
}
将显示所有可用端点。
.paths(PathSelectors.any("/mypath/**"))
将仅限制于 mypath.
中公开的端点
更新:2017 年 4 月 26 日,更新实施。感谢Andy Brown提供小费。
由于我们的编码约定,我们的端点没有特定的前缀,因此我正在寻找一种解决方案来排除执行器端点,而不是包含我自己的路径。
我想出了以下配置来仅排除执行器端点。 这样,一旦添加新端点,我就不必更新配置,也不必为自己的端点添加前缀以将它们与执行器端点区分开来。
/**
* This enables swagger. See http://localhost:8080/v2/api-docs for the swagger.json output!
* @param actuatorEndpointHandlerMapping this endpoint handler mapping contains all the endpoints provided by the
* spring actuator. We will iterate over all the endpoints and exclude them from the swagger documentation.
* @return the docket.
*/
@Autowired
@Bean
public Docket swaggerSpringMvcPlugin(final EndpointHandlerMapping actuatorEndpointHandlerMapping) {
ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.securitySchemes(securitySchemes())
.select();
// Ignore the spring-boot-actuator endpoints:
Set<MvcEndpoint> endpoints = actuatorEndpointHandlerMapping.getEndpoints();
endpoints.forEach(endpoint -> {
String path = endpoint.getPath();
log.debug("excluded path for swagger {}", path);
builder.paths(Predicates.not(PathSelectors.regex(path + ".*")));
});
return builder.build();
}
ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.securitySchemes(securitySchemes())
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/actuator.*")))
.build();
嗨,您可以排除正则表达式上的路径,并且可以链接它们。
通过
application.properties
文件将执行器端点移动到上下文路径中。
management.context-path=/manage
然后你可以从 swagger 中排除该路径
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/manage.*")))
.build();
}
您可能也想排除错误控制器
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("(/manage.*|/error)")))
.build();
}
替代方案:
a) 在正则表达式中排除带有 NOT 的路径?
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("^((?!/error).)*")) // exclude Basic Error Controller
.build();
}
b) 或链并否定谓词:
PathSelectors.any()
.and(PathSelectors.regex("/error").negate())
.and(PathSelectors.regex("/manage.*").negate());