Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring boot Configuration settings for different environment

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

like image 741
Temiloluwa Avatar asked Sep 15 '25 22:09

Temiloluwa


2 Answers

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

application.properties configuration

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 application-staging.properties content

and the dev could be configured to start on port 8989

application-dev.properties content

like image 174
Samuel Olufemi Avatar answered Sep 19 '25 10:09

Samuel Olufemi


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.

like image 44
SaleemKhair Avatar answered Sep 19 '25 11:09

SaleemKhair