【问题标题】:Gradle/Java: generate resources with executable Java classGradle/Java:使用可执行的 Java 类生成资源
【发布时间】:2020-07-08 08:04:26
【问题描述】:

情况如下:

  • 在 gradle 构建期间,我从依赖项中下载并解压缩资源
  • 项目中的一个类将处理这些资源,并生成要包含在项目中的新资源(作为生成的资源)

我设法想出了一个 hacky 解决方案,它在“类”任务之后运行生成器,并将资源写入 $buildDir/resources/main/schema

ext {
    schemaGenerator = "org.something.JsonSchemaGenerator"
    serviceContractsDir = file("$buildDir/service-contracts")
    schemaOutputDir = file("$buildDir/resources/main/schema")
}

task jsonSchemas(type: Exec) {
    dependsOn classes
    dependsOn serviceContracts

    commandLine "java", "-classpath", sourceSets.main.runtimeClasspath.getAsPath(), schemaGenerator, serviceContractsDir, schemaOutputDir
}

test.dependsOn jsonSchemas
assemble.dependsOn jsonSchemas

这很好用,然后生成的资源会包含在 JAR 中。
但是在上传artifacts时,它会上传JAR,而没有生成的资源。

我试图以正确的方式做到这一点:

ext {
    schemaOutputDir = file("$buildDir/generated-resources")
}

sourceSets.main.output.dir schemaOutputDir, builtBy: jsonSchemas

但是我最终得到了一个循环依赖,因为 Gradle 需要资源来构建类,而生成这些资源的任务也取决于类:

FAILURE:构建失败并出现异常。
出了什么问题:
以下任务之间的循环依赖:
:类
--- :jsonSchemas
--- :classes (*)

有没有办法将它们添加到正确的源集(如generated-resources),所以它们是

  • 对测试可见
  • 包含在生成的 JAR 中?

【问题讨论】:

  • 您可以添加一个额外的源集并将这个源集包含在生成的 jar 文件中。
  • 而不是测试/组装 - 尝试 jar.dependsOn - 即在创建 jar 之前进行修改

标签: java gradle


【解决方案1】:

添加一个独立于主 SourceSet 的新 SourceSet 应该可以解决问题:

task jsonSchemas(type: Exec) {
  // same as above
}

sourceSets {
  schema {
    output.dir(schemaOutputDir, builtBy: 'jsonSchemas')
  }
  test {
    resources.srcDirs += [sourceSets.schema.output]
  }
}

jar {
  from sourceSets.schema.output
}

【讨论】:

  • 工作就像一个魅力,我什至可以摆脱 dependsOn 声明,谢谢!
猜你喜欢
  • 2013-12-04
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2021-11-10
  • 1970-01-01
  • 1970-01-01
  • 2016-02-21
相关资源
最近更新 更多