Spring boot profiles - Separate your prod and dev configurations


In this blog post we are going to see how we can profile or run our code with different application configurations for different environments.

Assume that we have two environments, production and development. Normally we store our configurations in application.properties or application.yml file, to maintain different configurations we need to maintain separate configuration files to each environment.  Let's create our two configuration files application-prod.yml and application-dev.yml in resource directory.




In application.yml we define the active default profile, here it's dev profile, when we run the application it should load the dev configurations. You can switch between profiles using this configuration. 

Running the application

As you can see we should run the app in port 8080 in production and port 8081 in development. 

Using the command line.

- To run the jar with separate profile, build the application using mvn clean install, then run 
 java -jar target/profiles-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
As we can see the application started on port 8080 which is the production port. We should see application running on port 8081 when we run the application using dev profile.

Accessing configuration values.

- We can use several methods to access configuration values in our configuration file. I have created a test controller to test the values, you will find the repository link at the end of this blog post.
- Using @Value annotation we can easily access to individual values. We can access the configuration element following the same order in the configuration file like we are traversing a json object. ${spring.application.welcomeMessage} 

- We also can map these configuration to a model using @ConfigurationProperties("starting key of the config"). Create a model class and you will be able to access your configuration elements and in our test controller.

Run the application with two profiles and execute the below curl request and see the log output and response for different profiles.
curl http://localhost:8080/api/v1/test
- Run as prod 
 java -jar target/profiles-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
- Run as dev
 java -jar target/profiles-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

That's it for the intro post to using profiles in spring boot, as usual source code can be found at 

Thank you for reading this blog post. See you soon in a new post.


Post a Comment