2016-09-21 89 views
8

我想使用swagger-codegen来生成REST客户端和可能的静态HTML文档。如何使用gradle生成swagger.json?

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

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

但是有没有办法从我的Java代码直接获取swagger.json - 即使用源代码中的gradle生成swagger.json - 而不需要在Web容器中运行应用程序,并指定curl或浏览器它?

+0

我仍在研究它。 – tbsalling

+0

https://github.com/gigaSproule/swagger-gradle-plugin 你试过这个插件吗?它声称完全按照你的要求做。 –

+0

在使用swagger-gradle-plugin时,我遇到以下错误:com.fasterxml.jackson.databind.JsonMappingException:由于输入结束 at [Source:UNKNOWN;行:1,列:0] – lex

回答

1

的主要思想是招摇,Maven的插件和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() 

Here你可以找到这个例子。

2

这是一个有点老,但我想知道一模一样......总之我已经开始与研究:

  • 样本春天启动的应用程序暴露简约的REST API;
  • API方法的Swagger注释;
  • Springfox;
  • Gradle作为构建工具;

我设法生成JSON规范与使用两种不同的方法构建神器:

  1. 通过使用swagger-maven-plugin of kongchengradle port
  2. (不知道这是否值得,因为它反正启动服务器)通过执行生成规范的集成测试(Spring的模拟MVC)。我借用here的想法。

我总结了我的研究在一个简单的项目位于here。请参阅Automation部分。包括代码和示例。