使用 Javadocs 生成 Swagger 文档

2022-09-01 23:43:28

我想为一组现有的RESTful API构建Swagger文档。我有以下要求:

  1. 离线生成Swagger Doc(我用过 http://kongchen.github.io/swagger-maven-plugin/)。这个插件帮助我在编译时生成Swagger文档。
  2. 读取现有的 Javadoc,以便它们可以在 Swagger 文档中使用。

到目前为止,使用上述插件,我能够实现第1点。因此,对于现有的 REST 方法:

 /**
 * <p>
 * Gets the {@link DisplayPreferenceModel} with the name as provided in the parameter. The preference with the given name defined at the tenant or master level is returned.
 * This API gives us the preference if it is eligible for unauthorized access If it is not eligible it throws an Exception saying Authorization required.
 * </p>
 * @param preferenceName
 *            - The name of the preference.
 * @return {@link DisplayPreferenceModel}
 */
@RequestMapping(method = RequestMethod.GET, value = "/preferences/{preferenceName}")
@ApiOperation(value = "This API gives us the preference if it is eligible for unauthorized access If it is not eligible it throws an Exception saying Authorization required", 
                        notes = "No Notes please", response = DisplayPreferenceModel.class)
@ApiResponses(value = { 
                        @ApiResponse(code = 400, message = "Invalid preferenceName supplied"), 
                        @ApiResponse(code = 404, message = "Display Preference Not Found")
                      }
            )
public DisplayPreferenceModel getDisplayPreference( @PathVariable("preferenceName") final String preferenceName ) {
}

我能够生成Swagger文档。@ApiOperation和@ApiResponses的使用使我的文档看起来很棒。

但是,我的问题是,我是否可以使用Javadocs而不是让每个开发人员都创建@ApiOperation和@ApiResponses以便为我的团队节省时间?


答案 1

你可以使用 Enunciate 从 Javadoc 生成 swagger-ui,它有一个 Swagger 模块。首先,您需要将maven插件添加到pom文件中;例如:

<plugin>
        <groupId>com.webcohesion.enunciate</groupId>
        <artifactId>enunciate-maven-plugin</artifactId>
        <version>${enunciate.version}</version>
        <executions>
           <execution>
                  <goals>
                    <goal>docs</goal>
                  </goals>
                  <configuration>
                    <configFile>enunciate.xml</configFile>
                    <docsDir>${project.build.directory}</docsDir>
                  </configuration>
           </execution>
        </executions>
</plugin>

其中“enunciate.xml”包含您的项目特定配置,如下所示:

<enunciate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="http://enunciate.webcohesion.com/schemas/enunciate-2.0.0-M.3.xsd">

    <application root="/rest" />

</enunciate>

然后运行,它将从您的Javadoc生成Swagger文档文件。mvn compile


答案 2

似乎有javadoc doclet用于生成JSON Swagger资源列表:https://github.com/teamcarma/swagger-jaxrs-doclet


推荐