Gradle

Gradle and different environments

Gradle is a joy to work with. This „new“ build system is getting better and better. When switching from Maven you can get rid of all this xml stuff and write your tasks and so on in groovy. Speaking of switching, some users criticize the absence of a Gradle equivalent to Maven’s profiles.

According to Maven’s website: „Profiles are specified using a subset of the elements available in the POM itself (plus one extra section).“ Profiles are used to build for different environment, i.e. test, stage or production. In Maven, you can set a default profile, which is activated by default if none is specified. Otherwise the specified profile is used.

In Gradle there are no profiles and there is no environment variable out-of-the-box. But the good thing is, that Gradle can be extended easily.

First, you have to define a function which will be executed before all builds. The first lines of your build.gradle should look like this:

The loadConfiguration() method looks for an variable named env. This variable will be set when executing a build by:

Its value will be set to a project specific variable named environment. If the given env variable is omitted, a default value (‚dev‘) will be used. In your build you can now use this environment variable to, i.e. to set specific properties.

To achieve this you create a new file name environment.gradle with the following content:

It defines a new task, which sets up the correct environment by checking the corresponding variable (throws an error if the set environment is not supported). Everywhere in your build you can now do environment specific things.
To ensure, that the new task setUpEnvironmentConfiguration will be executed, you have to apply this new plugin in your build.gradle:

And now, if you want to execute a production specific task, all you have to do is to set the environment variable:

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

− 4 = 2