Spring Boot中如何针对特定profile隐藏OpenAPI 3下Swagger UI的指定端点
OpenAPI 3 隐藏Swagger UI端点的实现方案
方案1:仍使用SpringFox 3.x(支持OpenAPI3规范)
你原有的逻辑几乎不用改动,仅需将DocumentationType从SWAGGER_2替换为OAS_30即可:
@Bean public Docket postsApi() { return new Docket(DocumentationType.OAS_30) .groupName("public-api") .apiInfo(apiInfo()) .select() // 原有过滤逻辑保持不变,忽略标注了@IgnoreForProd的方法 .apis((handler) -> !handler.isAnnotatedWith(IgnoreForProd.class)) .build(); }
方案2:使用官方推荐的SpringDoc OpenAPI(适配OpenAPI3的主流方案)
SpringFox已经停止维护,更建议迁移到SpringDoc OpenAPI实现OpenAPI3规范,自定义注解过滤的实现方式如下:
- 保留你原有自定义的
@IgnoreForProd注解无需修改 - 新增配置类实现端点过滤逻辑:
@Configuration public class OpenApiConfig { @Bean public OpenApiCustomiser hideEndpointsWithIgnoreAnnotation() { return openApi -> openApi.getPaths().entrySet().removeIf(entry -> { PathItem pathItem = entry.getValue(); // 检查该路径下所有请求方法对应的方法是否标注了@IgnoreForProd注解 return pathItem.readOperations().stream() .anyMatch(operation -> Boolean.TRUE.equals(operation.getExtensions().get("x-ignore-for-prod"))); }); } // 配置扫描时将自定义注解识别为扩展属性 @Bean public OperationCustomizer operationCustomizer() { return (operation, handlerMethod) -> { if (handlerMethod.hasMethodAnnotation(IgnoreForProd.class) || handlerMethod.getBeanType().isAnnotationPresent(IgnoreForProd.class)) { operation.addExtension("x-ignore-for-prod", true); } return operation; }; } }
如果你不需要自定义注解,也可以直接在需要隐藏的类或方法上添加SpringDoc提供的
@Hidden注解,无需额外配置即可自动隐藏对应端点。
内容的提问来源于stack exchange,提问作者Igor
相关产品推荐
相关产品推荐

