How to set a system property before calling task in Gradle?

I expect this is very simple but am not finding the info I need and has seem to have become more complex than i initially thought.

I have 2 use cases;

1: launch jetty with embedded database (Task: launch)

2: launch jetty to use the on disk database (Task: launchOnDiskDB)

So my rational is to have 2 tasks and the user calls what task they want from the command line however, when they call the “launchOnDiskDB” then i do something like the following;

task launchOnDiskDB << {
             System.setProperty("spring.profiles.active", "database-static")
            tasks.launch.execute()
}

ie, simply chain back and execute Task: launch (all the second task does is sets a system property before delegating back)

The problem i’m having is that task.execute() seems not to be official supported & if I introduce dependsOn, the launch task runs before the task LaunchOnDiskDB has had a chance to set the system property…

How can this be done?

Thanks,

Ian.

1 Like

You could create two identical tasks, and use ‘doFirst { … }’ to set an additional system property for one of them.

Hi Peter,

That is what I tried but as i’m using a dependsOn it doesn’t call the doFirst (see below). Should it?

task launchInMemory(dependsOn: jettyRunWar) << {
    //not setting a property as in memory is the default.
}
  task launchOnDiskDB(dependsOn: jettyRunWar) << {
    doFirst
            {
                println "CallingStatic"
                System.setProperty("spring.profiles.active", "database-static")
            }
}

Thanks,

Ian.

1 Like

I didn’t know that ‘launch’ is once again delegating the work. In that case, you can add the system property depending on which task is going to get executed:

gradle.taskGraph.whenReady { graph ->
   if (graph.hasTask("launchOnDiskDb") {
    System.setProperty(...)
  }
}

Worked a treat - thanks v much…