我想使用 swagger-codegen 生成 REST 客户端以及可能的静态 HTML 文档。
但是,swagger-codegen 需要 swagger.json 进行输入。
我知道,我可以从配备 Swagger 的正在运行的 REST 服务器获取此信息。
但是有没有办法直接从我的 Java 代码中获取 swagger.json - 即使用源代码中的 gradle 生成它 - 而无需在 Web 容器中运行应用程序,并将
curl
或浏览器指向它?
这有点旧了,但我想知道完全相同......简而言之,我已经开始研究:
我设法使用两种不同的方法生成 JSON 规范作为构建工件:
这里。请参阅 Automation
部分。包括代码和示例。
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()
在这里您可以找到这个示例。