Home > Software design >  Java Spring boot Configuration settings for different environment
Java Spring boot Configuration settings for different environment

Time:04-12

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

CodePudding user response:

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.profile.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

CodePudding user response:

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 enviroment 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 usecase.

CodePudding user response:

Use Spring @Profile annotation

You can have environment specific property file

Ex: application-prod.properties application-dev.properties

  • Related