Creating and Using Profiles in Spring
Profiles are a core feature of the Spring Framework. They allow us to map different profiles for example, dev, test and prod. We can then activate the different profiles in the different environments.
Suppose you are working on a Spring Project and you have a development environment and a production environment.
Then, you have a media folder to store images on your development environment, usually most of the times your laptop.
If we were to shift to a production environment, most likely a server, we would most likely have to use a different path.
The main reason is because most likely in your laptop, you may have it in a path like mine : /home/kitush/media. You realize there is a big chance this path may not be recognized by the server.
The solution to this and many other instances of the same is to have different profiles that have different configurations.
In this story, I will be showing you how to create and use profiles in Spring.
- Add profiles to pom.xml
The xml code above creates two profiles, prod and dev. Note the activeByDefault property in the dev profile. This tells the pom file that the dev profile is active by default if nothing is specified
2. Create the Property Files
We have told the Spring project to expect two profiles, prod and dev. The next step is to create the two properties files.
We have a master application.properties file that is created by default. Navigate to where the application.properties is and create two files.
3. Edit the Properties Files
There is a distinction in the two files. The dev profile runs the Spring Application in port 8080 while prod does so in port 11417.
Secondly the media-url is different in the 2 profiles.
However note that, for constant properties they should be maintained in the master properties file : application.properties.
4. Tell the master properties file to activate specified profile.
Navigate to application.properties and add the following line so that it activates the specified profile.
5. Start project with a profile
You are now set to activate and use your profiles as shown below.
mvn spring-boot:run -Dspring-boot.run.profiles=prod
In the example above we activate the prod profile.
6. Build a profile
If you want to build a project with a specific profile, you can do so using this line:
mvn clean package -Pprod
The above line packages the project using the prod profile.
I hope this helps you understand how to create, activate and build profiles in Spring.