Search code examples
gradlegradlewgradle-plugin

Adding values into war file to yml file from values stored in a .properties file that are stored locally in gradle


I am trying to initialize my dataSource with the help of gradle however gradle is not putting the values into my yml that is stored in a .properties on my machine i.e ~/.gradle and I made a .properties file at that location.

In Gradle I made a method to get the values from the .properties file like so:

task copyDBConfig(type: Copy) {

    from 'src/main/resources'
    include 'app.yml'
    into 'build/resources/main'
    expand([
            DB_URI: project.findProperty("dbURI") ?: "",
            DB_USERNAME: project.findProperty("dbUsername") ?: "",
            DB_PASSWORD: project.findProperty("dbPassword") ?: "",
    ])
}

war.finalizedBy(copyDBConfig)

Then in my yml file I have:

spring:
  datasource:
      url: ${DB_URI}
      username: ${DB_USERNAME}
      password: ${DB_PASSWORD}
      driverClassName: oracle.jdbc.OracleDriver

However when I build the war file and look in the app.yml file the correct values are not there, just ${DB_URI} etc and NOT the strings it should be getting from my .properties file and inputting from into my app.yml file.

When I run the app I get the follow error:

java.sql.SQLException: Driver:oracle.jdbc.OracleDriver@af2025f returned null for URL:${DB_URI}

Note: Under build/resources/main/app.yml the values from my app.properties file are there, just not in the war file.


Solution

  • In your setup you instruct Gradle that after your war task is run it should always run the copyDBConfig task, which is too late, as the war is already built. Anyway making an own task for this is not the way to go. instead configure the processResources task like this:

    processResources {
        filesMatching('app.yml') {
            expand DB_URI: project.findProperty("dbURI") ?: "",
                   DB_USERNAME: project.findProperty("dbUsername") ?: "",
                   DB_PASSWORD: project.findProperty("dbPassword") ?: ""
        }
    }