SpringBoot : What are Profiles in Spring Boot Application

What are Profiles in Spring Boot

Profiles can be seen as different environments in spring boot application. Suppose you are working on an application where you have different staging environments like Dev, QA, UAT, Production etc. So you will have different configurations for each environment, for this kind of applications what you need is having different values that can be switched depending upon some flags.

In early days, people used to write configurations for all environments and comment the unused environments. But with Spring Boot we can do this without commenting any code by use of Profiles.

Suppose we have database name configurations for our application as follows

  • Dev   - ekiras_dev
  • QA    - ekiras_qa
  • UAT  - ekiras_uat
  • Prod  - ekiras

Now, we can use profiling in this case. How we will do it ? lets see

Creating Profiles in Spring Boot 

We will create different files for different environments and call then as profile in rest of the blog.
e.g

application-dev.properties
db.name=ekiras_dev

application-qa.properties
db.name=ekiras_qa

All the application files should either be under the resources folder or any folder that is in classpath. (resources/ is in class path by default).

Similarly you can have properties file for different profiles in the same folder. Each profile should be as application-{env}.properties

How Spring Boot Load Profiles

Spring boot by default loads application.properties from classpath if no profile is selected or specified. If you want to load profile specific properties then you need to tell spring boot application to load that profile, you can define this by the following ways

  • Specify the profile in application.properties as spring.profiles.active=dev this will enable the dev profile.
  • Specify the profile at run time as -Dspring.profiles.active=dev this will enable dev profile, also this will override any profile specified using step 1.

Spring looks for properties files as application-{profile}.properties where {profile} will be any profile you specify by using any of the steps mentioned above.

No comments :

Post a Comment