从 JavaDoc 生成 OpenAPI 描述

Generate OpenAPI descriptions from JavaDoc

我有一个应用程序提供 API 和 JAX-RS(Java API for RESTful Web 服务/ JSR-311).

出于文档目的,我根据 OpenAPI-Specification 提供了一个 URL,它由 Eclipse MicroProfile OpenAPI.

生成

一切正常,除了方法和参数的描述,我需要添加两次 - 在注释和 JavaDoc:

/**
 * Finds all resources with the given prefix.
 *
 * @param prefix
 *            the prefix of the resource
 * @return the resources that start with the prefix
 */
@GET
@Path("/find/{prefix}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "Finds all resources with the given prefix")
public List<Resource> find(
        @Parameter(description = "The prefix of the resource") 
        @PathParam("prefix") final String prefix) {
    ...
}

我知道没有运行时库可以读取 JavaDoc(因为它不是 class 文件的一部分),这是注释的主要原因。但是我想知道 OpenAPI 生成工具之一(Swagger、Eclipse MicroProfile OpenAPI、...)是否还有其他选项可以阻止我手动同步文档?

例如,在另一个项目中,我使用一个 doclet,它序列化 JavaDoc 并将其存储在 class 路径中,以向用户呈现 Beans API 文档在运行时。但即使我在这里使用这个 doclet,我也看不到在运行时向 OpenAPI 库提供 JavaDoc 描述的选项。

我知道我可以删除 JavaDoc,如果我的 API 的用户只使用“外语”,因为他们无论如何都看不到 JavaDoc .但是如果 API 的另一端是 JAX-RS 客户端会怎样?在那种情况下,JavaDoc 将是一个巨大的支持。

我知道了 运行 Eclipse Microprofile OpenAPI。

我必须自己定义 OASFilter:

public class JavadocOASDescriptionFilter implements OASFilter {

    @Override
    public void filterOpenAPI(final OpenAPI openAPI) {
        openAPI.getComponents().getSchemas().forEach(this::initializeSchema);
        openAPI.getPaths().forEach(this::initializePathItem);
    }

    private void initializeSchema(final String name, final Schema schema) {
        final SerializedJavadoc javadoc = findJavadocForSchema(name);
        if (StringUtils.isEmpty(schema.getDescription())) {
            schema.setDescription(javadoc.getTypeComment());
        }
        if (schema.getProperties() != null) {
            schema.getProperties().forEach((property, propertySchema) -> {
                if (StringUtils.isEmpty(propertySchema.getDescription())) {
                    propertySchema.setDescription(javadoc.getAttributeComments().get(property));
                }
            });
        }
    }
    ...
}

然后我不得不在 META-INF/microprofile-config.properties:

中声明过滤器
mp.openapi.filter=mypackage.JavadocOASDescriptionReader

有关此主题的讨论,请参见此处:https://github.com/eclipse/microprofile-open-api/issues/485