如何配置OpenAPI Generator:隐藏@Hidden接口文档仍生成客户端代码
解决方案
方案一:用自定义OpenAPI扩展分离文档显示与代码生成
@Hidden注解会直接把操作从OpenAPI规范中移除,导致生成器无法识别这些操作。这个方法通过自定义扩展标记操作,让Swagger UI隐藏它们,但操作仍保留在规范中供生成器使用:
替换
@Hidden为自定义扩展
在需要隐藏的接口方法上,使用@Operation的extensions属性添加x-hidden扩展:@Operation( summary = "内部专用接口", extensions = { @Extension( name = "x-hidden", properties = @ExtensionProperty(name = "value", value = "true") ) } ) @GetMapping("/internal/api") public ResponseEntity<String> internalApi() { return ResponseEntity.ok("internal data"); }配置Swagger UI过滤标记的操作
修改Swagger UI的初始化代码,添加插件过滤带有x-hidden: true的操作,使其不在文档中显示:const ui = SwaggerUIBundle({ url: "/v3/api-docs", dom_id: "#swagger-ui", deepLinking: true, plugins: [ { statePlugins: { spec: { wrapSelectors: { allowOperation: (originalSelector) => (state, operation) => { // 仅显示未标记x-hidden的操作 return originalSelector(state, operation) && !operation.extensions?.['x-hidden']; } } } } } ] });这样操作会保留在规范里,生成器正常生成代码,Swagger UI中则看不到这些接口。
方案二:保留@Hidden注解,调整规范与生成器配置
如果必须使用@Hidden,可以通过以下步骤让操作留在规范中,并强制生成器生成代码:
让SpringDoc保留
@Hidden操作到规范
默认SpringDoc会移除@Hidden操作,需要自定义处理让它们保留并标记为hidden: true:- 创建
OperationCustomizer组件:@Component public class HiddenOperationHandler implements OperationCustomizer { @Override public Operation customize(Operation operation, HandlerMethod handlerMethod) { boolean isHidden = handlerMethod.hasMethodAnnotation(Hidden.class) || handlerMethod.getBeanType().isAnnotationPresent(Hidden.class); if (isHidden) { operation.setHidden(true); return operation; } return operation; } } - 在
application.properties中关闭自动隐藏:springdoc.api-docs.hide-hidden-operations=false
- 创建
生成客户端时强制包含hidden操作
使用openapi-generator-cli生成客户端时,添加参数--skip-hidden-operations false,或者在配置文件中设置:{ "skipHiddenOperations": false }这样生成器会处理规范中标记为
hidden: true的操作,生成对应的客户端存根,而Swagger UI默认会隐藏这些操作。
内容的提问来源于stack exchange,提问作者spal
相关产品推荐
相关产品推荐

