Spring Profiles

    +
    Spring boot provides out of the box Spring Profiles capabilities to maintain your environment specific(e.g. dev, prod) application configuration. For example, its common practice to use the different database for development and test. It can achieve very easily though spring profiles.

    Release date: January 2021 | Spring Boot: 2.4.x | Revision: 1

    Action: Spring Profiles

    Use .yaml Configurations instead of .properties. Spring supports both yaml and properties file format for its configurations. As kubernetes and docker-compose both uses yaml file for its configuration, knowledge of yaml file will help to work with kubernetes and docker-compose. It’s also comparatively easy to design complex configuration profiles in yaml file.

    Create Spring Profiles

    Spring initializr generates application.properties for spring configuration. We will move into YAML (.yml) based configuration by renaming it to application.yml. Initially we will only configure dev profile. Do the following to create spring profiles.

    1. Create application-dev.yml file. Add port configuration to the file.

      application-dev.yml
      server:
        port: 8081
    2. Rename application.properties to application.yml.

    3. Add spring profiles active configuration to application.yml.

      application.yml
      spring:
        profiles:
          active: dev

    Spring changes its Config File Processing in version 2.4. Older configurations (before Spring version 2.4) may require migration to support new spring versions capabilities.

    During build, we can activate spring profiles based on build profile. In real development scenario, during dev build developer may want to activate the dev spring profile as well. It’s possible through gradle build script configuration. We will update further our profiles.

    1. Update spring profiles active configuration to application.yml.

      application.yml
      spring:
        application:
          name: bank
        profiles:
          # The commented value for `active` can be replaced with valid Spring profiles to load.
          # Otherwise, it will be filled in by gradle when building the JAR file
          # Either way, it can be overridden by `--spring.profiles.active` value passed in the commandline or `-Dspring.profiles.active` set in `JAVA_OPTS`
          active: #spring.profiles.active#
    2. Add spring profile switching logic to root build.gradle file. This code snippet will change the active profile value based on buildProfile value.

      build.gradle
      processResources {
          filesMatching("application.yml") {
              filter {
                  it.replace("#spring.profiles.active#", buildProfile)
              }
          }
      }

    It is still possible to override spring.profiles.active at commandline.

    java -jar bank-0.0.1.jar --spring.profiles.active=prod

    Learn More

    Project Code