我希望 Gradle 在构建项目时将
version.properties
文件写入我的 Java 类路径。
我有这样的任务
task createVersionPropertiesFile() {
def outputFile = new File(projectDir, "src/main/java/org/example/lpimport/version.properties")
outputs.file outputFile
doLast {
outputFile.text =
"""# generated by Gradle
version=$version
revision=${getSvnRevision()}
buildtime=${new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())}
"""
}
outputs.upToDateWhen { false }
}
我这样包含它:
build.dependsOn createVersionPropertiesFile
当我在 Eclipse 中运行 Gradle
build
任务时,文件按预期创建! ✅
如果我在 Eclipse 中运行我的应用程序,生成的
version.properties
文件可以由我的应用程序加载。 ✅
props.load( Main.class.getResourceAsStream( "version.properties" ) );
但是
version.properties
文件不会成为 myproject-1.0.0.jar
发行版中构建的
myproject-1.0.0.zip
的一部分,尽管它驻留在普通的类路径包中。 ❌如何让 Gradle 将即时生成的
version.properties
包含在 JAR 中?
.properties
文件写入
src/main/resources
而不是
src/main/java
:
def outputFile = new File(projectDir, "src/main/resources/org/example/lpimport/version.properties")
compileJava
任务取决于我的自定义任务:
compileJava.dependsOn createVersionPropertiesFile
.properties
文件位于
src/main/java
下面,则它似乎会被 Gradle 忽略(通过其 jar 任务??)。现在它可以工作了,我构建和打包的应用程序可以在启动时显示其版本属性。
https://github.com/microsoft/thrifty/blob/master/thrifty-gradle-plugin/build.gradle#L45
下面完整复制了链接的片段,并附有额外的注释解释了为什么会这样:
def versionTask = tasks.register("generateVersionProps") { t ->
// Because this is an ephemeral file - generated from other sources -
// it's best to put it under the build dir, conventionally under 'build/generated'.
def generatedResourcesDir = project.layout.buildDirectory.dir(["generated", "sources", "thrifty", "src", "main", "resources"].join(File.separator))
def outputFile = generatedResourcesDir.map {it -> it.file("thrifty-version.properties") }
// By marking the properties we're using as inputs, Gradle can avoid
// regenerating this file when nothing has changed.
t.inputs.property("thrifty-version", VERSION_NAME)
t.inputs.property("kotlin-version", libs.versions.kotlin.get())
// Marking our output directory as such tells Gradle what task generates it,
// saving us from having to manually wrangle 'dependsOn', etc.
t.outputs.dir(generatedResourcesDir).withPropertyName("outputDir")
doFirst {
outputFile.get().getAsFile().with {
it.delete()
it << "THRIFTY_VERSION=${VERSION_NAME}\n"
it << "KOTLIN_VERSION=${libs.versions.kotlin.get()}\n"
}
}
}
clean {
// Make 'clean' aware of the resource we're generating.
// NB: This works (deleting the task) because we gave the task an output dir.
delete versionTask
}
// Finally! We register the output of the version task as
// a resources sourceSet. This causes our generated dir to
// be included in the build.
sourceSets {
main {
resources {
srcDir versionTask
}
}
}