I am using maven with java Spring-boot.
How can efficiently handle configuration for different environment? For instance, if I am on staging use this port, if I am on dev, use this port
Currently, I change all the necessary settings in the application.properties each time I move to a different environment
You can create different application.properties file for different environment. The environment name should be appended to the filename and separated with dash (-). For example,
you can have  application-dev.properties for dev environment , you can also have 'application-staging.propertiesfor staging environmentapplication-prod.properties` for production environment.
To activate each environment, pass it as a flag when are starting your .jar application for example
java -jar myapp.jar --spring.profiles.active=staging
or you can define the active profile inside application.properties.
I.e (In the example below , your application will make use of the configuration inside application-staging.properties )
spring.profiles.active=staging #comment out to switch away from staging
#spring.profiles.active=dev # uncomment to set active profile to dev
#spring.profiles.active=prod # uncomment to set active profile to prod

You can now have different settings based on different environment in the custom created files.
For instance the staging environment could be configured to start on port 8888 as shown below

and the dev could be configured to start on port 8989

In Spring Boot, there is a convention of using a property file or a yaml file, the pattern used for file naming is application-{env}.[ yaml | properties ].
Specifying the env variable can be passed using spring.profiles.active property, e.g.
Say you have a Spring config file named application-test.yaml then:
pom.xml
.
.
<properties>
 
 <spring.profiles.active>${environment}</spring.profiles.active>
</properties>
.
.
To use a different environment for each Maven build you'll need to use Maven profiles, e.g.
pom.xml
<profiles>
  <profile>
    <id>test</id>
    <properties>
      <property>
        <name>environment</name>
        <value>test</value>
      </property>
    </properties>
    ...
  </profile>
</profiles>
This allows you to control the environment from the console:
$ mvn clean verify -P test
A quick search for Maven profiles and Spring profiles will probably get you what you need for your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With