您可以添加一个任务,将您喜欢的任何值写入 java Properties 文件,如下所示:
apply plugin: 'java'
apply plugin: 'application'
def generatedResourcesDir = new File(project.buildDir, 'generated-resources')
tasks.withType(Jar).all { Jar jar ->
jar.doFirst {
def props = new Properties()
props.foobar = 'baz'
generatedResourcesDir.mkdirs()
def writer = new FileWriter(new File(generatedResourcesDir, 'build.properties'))
try {
props.store(writer, 'build properties')
writer.flush()
} finally {
writer.close()
}
}
}
sourceSets {
main {
resources {
srcDir generatedResourcesDir
}
}
}
mainClassName = 'BuildProps'
请注意,在根项目的构建输出目录中创建了一个目录(称为 generate-resources,尽管您可以在合理范围内随意调用它)。由于在任何jar 任务之前运行自定义任务,属性文件随后被写入此目录。最后,将 generated-resources 目录添加到 resources 源集。这意味着它将成为生成的 jar 文件中的资源,因此可以像任何其他资源一样访问;例如:
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
class BuildProps {
public static void main(String[] args) {
try (InputStream inputStream =
BuildProps.class.getClassLoader().getResourceAsStream("build.properties")) {
Properties props = new Properties();
props.load(inputStream);
System.out.println("Build properties:");
System.out.println("foobar=" + props.getProperty("foobar", ""));
} catch (IOException e) {
e.printStackTrace();
}
}
}
将打印:
Build properties:
foobar=baz
至于您想要的特定属性,您可以这样设置:将props.foobar = 'baz' 行替换为以下内容
def dependenciesProp = ''
for (def dependency : project.configurations.runtime.allDependencies) {
dependenciesProp += dependency.toString() + ','
}
props.dependencies = dependenciesProp
props.runtimename = project.configurations.runtime.name
def artifactsProp = ''
for (def artifact : project.configurations.runtime.allArtifacts) {
artifactsProp += artifact.toString() + ','
}
props.artifacts = artifactsProp