Gradle - Create .properties file before / as part of each build and include it into JAR

Viewed 102

I want Gradle to write a version.properties file into my Java classpath whenever I build the project.

I have a task like this

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 }
}

And I include it like this:

build.dependsOn createVersionPropertiesFile

When I run the Gradle build task in Eclipse, the file is created as expected! ✅

If I run my application in Eclipse, the generated version.properties file can be loaded by my application. ✅

props.load( Main.class.getResourceAsStream( "version.properties" ) );

But the version.properties file will not be part of the built myproject-1.0.0.jar inside the myproject-1.0.0.zip distribution, although it resides in a normal class path package. ❌

How can I make Gradle include the on-the-fly generated version.properties inside the JAR?

1 Answers

I solved the problem by making two changes:

  • Write the .properties file to src/main/resources instead of src/main/java:

    def outputFile = new File(projectDir, "src/main/resources/org/example/lpimport/version.properties")
    
  • Make the compileJava task depend on my custom task:

    compileJava.dependsOn createVersionPropertiesFile
    

It seems the .properties file is ignored by Gradle (by its jar task??) if it resides below src/main/java.

Now it works and my built and packaged application can display its version properties on startup.

Related