从 JavaDoc 生成 OpenAPI 描述

Tob*_*fke 7 jax-rs swagger openapi

我有一个应用程序,它提供了一个带有JAX-RS 的API(用于 RESTful Web 服务的 Java API/JSR-311)。

出于文档目的,我根据OpenAPI 规范提供了一个 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) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Tob*_*fke 4

我使用 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));
                }
            });
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后我必须在以下位置声明该过滤器META-INF/microprofile-config.properties

mp.openapi.filter=mypackage.JavadocOASDescriptionReader
Run Code Online (Sandbox Code Playgroud)

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