Java代码:
public static String VERSION = "version_number";
升级build.gradle
version = '1.0'
如何从年级设置Java代码版本?该版本必须在源代码中。
有方便的方法吗?一种不太好的方法:
答案 0 :(得分:1)
一种方法类似于您不太好的方法,但是稍微容易一些。考虑templates/BuildInfo.java
中的文件:
package __PACKAGE;
public class BuildInfo {
private static final String version = "__VERSION";
private static final String buildTimestamp = "__BUILD_TIMESTAMP";
public String toString() {
return "version : " + version + "\n" +
"build timestamp : " + buildTimestamp + "\n";
}
}
然后可以在compileJava
任务中首先将该文件打上信息,然后写入src/main/java/your/package/BuildInfo.java
:
def targetPackage = 'net/codetojoy/util'
def targetPackageJava = 'net.codetojoy.util'
def appVersion = project.appVersion // from gradle.properties
def buildTimeStamp = new Date().toString()
compileJava {
doFirst {
ant.mkdir(dir: "${projectDir}/src/main/java/${targetPackage}")
def newBuildInfo = new File("${projectDir}/src/main/java/${targetPackage}/BuildInfo.java")
def templateBuildInfo = new File("${projectDir}/templates/TemplateBuildInfo.java")
newBuildInfo.withWriter { def writer ->
templateBuildInfo.eachLine { def line ->
def newLine = line.replace("__PACKAGE", targetPackageJava)
.replace("__VERSION", appVersion)
.replace("__BUILD_TIMESTAMP", buildTimeStamp)
writer.write(newLine + "\n");
}
}
}
}
提供了一个工作示例here。一切都将存储在源代码控制 中,src/main/java/your/package/BuildInfo.java
文件除外。请注意,该版本将存储在gradle.properties
中。
答案 1 :(得分:1)
我会做与迈克尔·复活节类似的事情,但有这些区别
src/main/java
和$buildDir/generated/java
)分开存储。这具有不需要自定义gitignore $buildDir
的子目录中生成,以便清理任务将删除生成的源src/template/java
中的所有内容都将替换为令牌。您将来可以轻松添加更多模板 src/template/java/com/foo/BuildInfo.java
package com.foo;
public class BuildInfo {
public static String getVersion() {
return "${version}";
}
}
build.gradle
task generateJava(type:Copy) {
def templateContext = [version: project.version]
inputs.properties templateContext // for gradle up-to-date check
from 'src/template/java'
into "$buildDir/generated/java"
expand templateContext
}
sourceSets.main.java.srcDir "$buildDir/generated/java" // add the extra source dir
compileJava.dependsOn generateJava // wire the generateJava task into the DAG