Using a Java source file to manage the version of your project is backwards. You should let your build system—in this case, Gradle—manage the version. 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.
Within the build script this is easily accomplished; you simply have to reference the version property everywhere you need it. 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).
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:
- Create a properties file as a resource and use the
processResources Gradle task to inject the project's version into said properties file. Then read the resource at runtime to get the application version.
- Create a custom Gradle task which generates a properties file as a resource. Then read the resource at runtime to get the application version.
- Create a custom Gradle task which generates the Java source file (e.g.
AppVersion.java) that represents your application's version.
- Use the
jar Gradle task to set the Implementation-Version attribute of the manifest. Then read this attribute at runtime to get the application's version.
- If using Java 9+ and modules then you can have the
compileJava Gradle task set the module version. 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). 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).
buildSrc, but your build won't be modifying it. Besides, builds can run on your PC, CI server, another dude's Mac, how'd all these versions remain in sync?String myVersion: "1.0"In build.gradle:version = myVersionbuildSrc. What doesn't make sense is that you want to have a variable that you don't know how to increment.