Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle : Copy different properties file depending on the environment and create jar

I am evaluating gradle for my spring boot project. Everything seems to work but here is where I am stuck. I have 2 properties file. One for prod i.e.:

application_prod.properties

and another for qa i.e.:

application_qa.properties

My requirement is such that while I build (create jar file) the project from gradle, I've to rename the properties file to

application.properties

and then build the jar file. As far as I know, gradle has a default build task. So here I've to override it such that it considers only the required properties file and rename it and then build depending on the environment.

How can I achieve this?

like image 463
15R6 Avatar asked Apr 21 '16 13:04

15R6


People also ask

How do I pass system properties in Gradle?

System propertiesUsing the -D command-line option, you can pass a system property to the JVM which runs Gradle. The -D option of the gradle command has the same effect as the -D option of the java command.

How do I pass environment variables in Gradle task?

If you are using an IDE, go to run, edit configurations, gradle, select gradle task and update the environment variables. See the picture below. Alternatively, if you are executing gradle commands using terminal, just type 'export KEY=VALUE', and your job is done.

Does Gradle build create jar?

In this tutorial, we will show you how to use Gradle build tool to create a single Jar file with dependencies. Tools used : Gradle 2.0.


1 Answers

What you need to do is to override processResources configuration:

processResources {
    def profile = (project.hasProperty('profile') ? project.profile : 'qa').toLowerCase()
    include "**/application_${profile}.properties"
    rename {
        'application.properties'
    }
}

With the following piece of code changed you will get the output below:

$ ./gradlew run -Pprofile=PROD
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
LOL
Profile: PROD

BUILD SUCCESSFUL

Total time: 3.63 secs

$ ./gradlew run -Pprofile=QA  
:compileJava UP-TO-DATE
:processResources
:classes
:run
LOL
Profile: QA

BUILD SUCCESSFUL

Total time: 3.686 secs

$ ./gradlew run             
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:run
LOL
Profile: QA

BUILD SUCCESSFUL

Total time: 3.701 secs

Demo is here.

like image 163
Opal Avatar answered Jan 01 '23 20:01

Opal