Setting Spring Profiles in Gradle

Here are a few ways I've found to set the profile of your Spring application at build time in Gradle.

First, a tried-and-true approach would be to set the environment in code. Something like this in your Main() method or wherever you're creating your Spring Context.

public static void main(String[] args) {

    System.setProperty("spring.profiles.active", "production");

    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
    ctx.register(SpringConfiguration.class);
    ctx.refresh();

    SpringApplication app = BeanFactoryUtils.beanOfType(ctx, SpringApplication.class);
    app.init();
}

But we don't want to hard-code the profile so we're going to do it in Gradle. I'll list a few options and finish with the approach I feel is best for me.

Using the IDE

You can set the profile in IntelliJ or Eclipse as shown in the VM options below in IntelliJ.

This won't work, however, unless you tell the Gradle bootRun task to pull-in the System Properties.

bootRun {
    addResources = false
    systemProperties = System.properties
    main = 'com.nixmash.springdata.jpa.Launcher'
}

Setting the Profile in a Separate Gradle Task

You could use a new Gradle task if you want to option of building your application Profile-free.

task production << {
    bootRun.systemProperty 'spring.profiles.active', 'production'
}

bootRun {
    addResources = false
    main = 'com.nixmash.springdata.jpa.Launcher'
}

We're setting the profile in our production task, so we can run our app like so.

$ gradle production bootRun

That gives us the option to run $gradle bootRun without a profile setting. Otherwise we'd run the two tasks, production and bootRun as shown above. This is also a good approach is you have several different profiles. You could create different tasks like production, but called development, or whatever, in which case you could fire-up the given profile by entering it on the command line. You CAN, of course, name the task anything at all. It by no means has to be the name of the task.

$ gradle development bootRun

Speaking of using Gradle on the command line and profile settings, here's another option from Tomas Lin.

$ SPRING_PROFILES_ACTIVE=dev,hsqldb ./gradlew bootRun

As a sidebar, in the same post is a good tip for setting a server port dynamically.

SERVER_PORT=9000 ./gradlew bootRun

Current Vote Winner

My current favorite approach for setting the Spring Profile in Gradle at build time is to simply add the property in the Gradle bootRun task. Either of the two commented lines will work. This approach wins because you're typically always going to run bootRun with the same profile and changing it is easy enough.

bootRun {
    addResources = false
//    environment 'spring.profiles.active', 'production'
//    systemProperty 'spring.profiles.active', 'production'
    main = 'com.nixmash.springdata.jpa.Launcher'
}

 

More Like This Post