[英]Using java variable in build.gradle
Is there any way to use a java variable in my build.gradle version field so I don't need to manually change the build script everytime I make a new build?有什么方法可以在我的 build.gradle 版本字段中使用 java 变量,这样我每次进行新构建时都不需要手动更改构建脚本?
So something like this所以像这样
group = 'project_name'
version = <insert variable from java file>
sourceCompatibility = '1.8'
Using a Java source file to manage the version of your project is backwards.使用 Java 源文件来管理项目的版本是向后的。 You should let your build system—in this case, Gradle—manage the version.
您应该让您的构建系统(在本例中为 Gradle)来管理版本。 When you update the version in Gradle you should have setup the build in such a way that the new version is propagated throughout the project.
当您更新 Gradle 中的版本时,您应该以这样一种方式设置构建,以便新版本在整个项目中传播。
Within the build script this is easily accomplished;在构建脚本中,这很容易实现; you simply have to reference the
version
property everywhere you need it.您只需在需要的任何地方引用
version
属性。 The concept isn't any different than passing data around in your application.这个概念与在应用程序中传递数据没有任何不同。 Remember that, in Gradle, the build script is written in Groovy or Kotlin and normal programming logic applies (the build script is essentially an object which implements both
org.gradle.api.Project
and org.gradle.api.Script
). Remember that, in Gradle, the build script is written in Groovy or Kotlin and normal programming logic applies (the build script is essentially an object which implements both
org.gradle.api.Project
and org.gradle.api.Script
).
The more difficult part is making sure your application can see the version without having to update the version in both the build script and the source code.更困难的部分是确保您的应用程序可以看到版本,而无需在构建脚本和源代码中更新版本。 There are, however, a number of ways to accomplish this, such as:
但是,有多种方法可以实现这一点,例如:
processResources
Gradle task to inject the project's version into said properties file.processResources
Gradle 任务将项目的版本注入到所述属性文件中。 Then read the resource at runtime to get the application version.AppVersion.java
) that represents your application's version.AppVersion.java
)。jar
Gradle task to set the Implementation-Version
attribute of the manifest.jar
Gradle 任务设置清单的Implementation-Version
属性。 Then read this attribute at runtime to get the application's version.compileJava
Gradle task set the module version.compileJava
Gradle 任务设置模块版本。 Then you can read the module version at runtime. You might also want to consider keeping the version in the gradle.properties
file and reading it from there into your build script (Gradle provides an API for this).您可能还需要考虑将版本保留在
gradle.properties
文件中,并将其从那里读入您的构建脚本(Gradle 为此提供了 API)。 That way when you update the version the build script doesn't have to be recompiled (at least that's the case with the Kotlin DSL).这样,当您更新版本时,不必重新编译构建脚本(至少 Kotlin DSL 就是这种情况)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.