如何使用gradle生成swagger.json?

问题描述 投票:0回答:3

我想使用 swagger-codegen 生成 REST 客户端以及可能的静态 HTML 文档。

但是,swagger-codegen 需要 swagger.json 进行输入。

我知道,我可以从配备 Swagger 的正在运行的 REST 服务器获取此信息。

但是有没有办法直接从我的 Java 代码中获取 swagger.json - 即使用源代码中的 gradle 生成它 - 而无需在 Web 容器中运行应用程序,并将

curl
或浏览器指向它?

java swagger swagger-codegen
3个回答
9
投票

这有点旧了,但我想知道完全相同......简而言之,我已经开始研究:

  • 公开简约 REST API 的示例 Spring Boot 应用程序;
  • API 方法上的 Swagger 注释;
  • 春狐;
  • Gradle 作为构建工具;

我设法使用两种不同的方法生成 JSON 规范作为构建工件:

  1. 通过使用 kongchen 的 swagger-maven-plugin 的 gradle 端口
  2. (不确定这是否重要,因为它无论如何都会启动服务器)通过执行生成规范的集成测试(Spring 的模拟 MVC)。我从
  3. 这里借用了这个想法。
我在一个简单的项目中总结了我的研究,位于

这里。请参阅 Automation

 部分。包括代码和示例。


2
投票
主要思想是将 swagger-maven-plugin 和你的 java 类添加到类路径中,以便 buildScript 能够在 gradle 中使用它们,如下所示:

buildscript { repositories { mavenCentral() } dependencies { classpath files(project(':swagger-maven-example').configurations['runtime'].files) classpath files(project(':swagger-maven-example').sourceSets['main'].output.classesDir) } }

依赖项中的第一行从子项目获取 swagger 库,第二行获取应包含 swagger 注释的类。

之后你可以在gradle中调用maven插件作为一个简单的java类:

// a trick to have all needed classes in the classpath def customClass = new GroovyClassLoader() buildscript.configurations.classpath.each { // println it.toURI().toURL() customClass.addURL(it.toURI().toURL()) } final ApiDocumentMojo mavenTask = Class.forName('com.github.kongchen.swagger.docgen.mavenplugin.ApiDocumentMojo',true, customClass).newInstance( apiSources: [ new ApiSource( springmvc: false, locations: ['com/github/kongchen/swagger/sample/wordnik/resource'], schemes: ['http', 'https'], host: 'petstore.swagger.wordnik.com', basePath: '/api', info: new Info( title: 'Swagger Maven Plugin Sample', version: 'v1', description: 'This is a sample for swagger-maven-plugin', termsOfService: 'http://www.github.com/kongchen/swagger-maven-plugin', contact: new Contact( email: '[email protected]', name: 'Kong Chen', url: 'http://kongch.com' ), license: new License( url: 'http://www.apache.org/licenses/LICENSE-2.0.html', name: 'Apache 2.0' ) ), outputPath: file("${buildDir}/swagger/document.html").path, swaggerDirectory: file("${buildDir}/swagger/swagger-ui").path, templatePath: file("${project(':swagger-maven-example').projectDir}/templates/strapdown.html.hbs") ) ] ) // maven plugin mavenTask.execute()

在这里您可以找到这个示例。


0
投票
您是否设法使用 gradle 从 java 生成 swagger.json 文件?

© www.soinside.com 2019 - 2024. All rights reserved.