首页 > 解决方案 > 如何根据 Swagger 的自定义 Annotation 创建注释/描述

问题描述

我有一个 Springboot Rest 应用程序,其中有自动转换 API 和参数的注释。

我有自定义注释,其中包含一些注释,如何在 OpenAPI 3 中将其生成到我的招摇页面?

Ex:
@RestController
Class Controller {

@GetMapping(/test/result/)
@CustomAnnotation(value = "This description should come in swagger")
void method() {
}
}

标签: spring-bootswaggerswagger-uiopenapispringdoc-openapi-ui

解决方案


SpringDoc 允许您通过实现自己的 Customizer bean 来自定义生成的 OpenAPI 规范。

有很多定制器界面可用于定制,但最有用的是OperationCustomizerParameterCustomizerPropertyCustomizer.

以下是您的用例的操作定制器示例。

@Component
public class OperationCustomizer implements org.springdoc.core.customizers.OperationCustomizer {
    @Override
    public Operation customize(Operation operation, HandlerMethod handlerMethod) {
        CustomAnnotation annotation = handlerMethod.getMethodAnnotation(CustomAnnotation.class);
        if (annotation != null) {
            operation.description(annotation.value());
        }
        return operation;
    }
}

在这里,您可以找到使用自定义注释和定制器的项目示例。

这里是一个基于 @NonNull 注释修改生成规范的项目示例。


推荐阅读