Spring Boot Profiling – Configure for Different Environments

Spring Boot Profiling:-

Spring Boot Profiling provides a way to segregate parts of your application configuration and make it only available in the certain environment.It is one of those concepts which we don’t use if we are working in development or just for learning purpose. Spring Boot Profiling is needed for applications which need’s to load different configurations for different environments Such as QA, DEV OR PROD.

In this Post, we will see how we use different database Url for different environments and let spring boot load the Url based on environment specified or profiling mentioned.

In order to demonstrate Spring Boot Profiling, we will create two different property files for prod and QA environments. I am using PostgreSQL for dev environment and MySQL for prod environment. Let us Check the Project structure below.

Project Structure:-

Let’s check property files for different environments, we are using different property files for different config in our application.Let’s configure database URL for those property files.

application.properties

1

2

3

4

5

6

spring.jpa.hibernate.ddl-auto=create

spring.datasource.url=jdbc:mysql://localhost:3308/profiling

spring.datasource.username=root

spring.datasource.password=root

spring.profiles.active=prod

This is the default properties for Spring Boot. You can see it has a property spring.profiles.activeas a prod, this means that spring boot will look for the default property as application-prod.properties.The configuration written in the application-prod.properties is loaded by default if we don’t specify any profile while running my spring boot application.

We can also specify active profiles inapplication.properties and replace them using the command line switch.We can also specify multiple active profiles, for example:- spring.profiles.active=dev, prod in our properties file

Here we are printing out the database URL which is getting loaded in Spring Boot Profiling .

Running the Application:-

Navigate to the Project directory and runmvn clean install .

Now type this command mvn spring-boot: run, once you run this maven command you will see something like this below:-

You can see our prod database Url is now loaded by default.Now let’s assume I am in development machine and want to run development database config, so I need to run my application in development mode. Please run following command line switch to switch to your dev profile.

output:-

Here the Postgresql database url must be loaded if everything is correct.

This is how we do profiling in a real-world application, spring also provides the Programmatic way of doing profiling. Please check out this link to find about Programmatic Way of Spring Boot Profiling.