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.
application-prod.yml
application-dev.ymlapplication.yml
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
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}
curl http://localhost:8080/api/v1/test
- Run as prod
java -jar target/profiles-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod
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.
Great article to know about Spring boot profiles :)
ReplyDeleteThank you very much keveesha
DeleteGreat Job Rajith.!
ReplyDeleteThank you Priyanka
DeleteLove this article.
ReplyDeleteThank you very much
Delete