APITROVE BLOG

How to add profile-based ports without creating configuration files

1. Overview

Often we use separate "dev" and "prod" profile properties/yaml files to configure development or production environment.

But what if we want to set up ports for our applications based on some other profile criteria but do not want to create their properties files separately? We shall look into that.

2. Configruations Requirements

Let's say we want to add following configurations in our spring boot application:

deployment:blue -> port:1122
deployment:green -> port:1133

3. pom.xml File Configurations:

We shall add new profiles named 'blue' and 'green' in pom.xml file as follows:

<profiles>
        <!-- blue -->
        <profile>
            <id>blue</id>
            <properties>
                <spring.profiles.active>prod</spring.profiles.active>
                <custom.port>1122</custom.port>
            </properties>
        </profile>
        <!-- green -->
        <profile>
            <id>green</id>
            <properties>
                <spring.profiles.active>prod</spring.profiles.active>
                <custom.port>1133</custom.port>
            </properties>
        </profile>
<!-- dev -->
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <spring.profiles.active>dev</spring.profiles.active>
                <custom.port>8080</custom.port>
            </properties>
        </profile>
    </profiles>

Note: You can add new profiles along with exisitng profiles.

4. properties File Configuration:

1. Now, let's add following lines in application.properties file:

server.port= @custom.port@

For application.yaml file:

server:
  port: '@custom.port@'

2. add following config in application.properties/yaml file to activate the desired profile:

spring.profiles.active= @spring.profiles.active@ #(for properties file)
spring:
  profiles:
    active: '@spring.profiles.active@' #(for yaml file)

Your configurations are complete here.

Note: Spring boot picks only 'application.properties' or 'application.yaml' files by default. So, be mindful of correct spellings.

5. Running application

Now, let's run the application with maven command:

./mvnw clean -Pblue spring-boot:run

This will run application with port 1122. Note that the active profile shown in application logs will be "prod".

This settings is helpful when you want to run profile-specific properties file with customized port.