Skip to main content

How to read different properties file based on Spring Profile in a Spring MVC project

How to read different properties file based on Spring Profile in a Spring MVC project


This tutorial aims towards providing a solution for selecting properties file based on the profile injected for a Spring MVC application at run time.
Technologies used

  • Spring 3.1
  • Java 8

How to inject Spring profile

Spring profiles can be passed as an environment variable like
-DSPRING_PROFILES_ACTIVE="dev" where dev is the profile name

  • If you are using Eclipse You can add an environment variable say in local tomcat server by doing Right click on Your_Project -> Run AS Config –> Apache tomcat -> VM arguments add -DSPRING_PROFILES_ACTIVE=”dev”, as shown below.
  • If you are using Docker you can have a look at this link.

How to get the Spring Profile within servlet context

If you have set the profile on the server and want it to retrieve it within your application you can use System.getProperty or System.getenv methods.
Here is the code which fetches the profile and defaults it to a local profile, if no profile has been found.

Also if you are using Java configuration for spring that is, extending a class from WebApplicationInitializer you need to set the profile in servlet context by using setinitParamter() method which has been added as the last line in above method.


Picking the right property file based on profile

If you have come this far without any problems then the next step is to create a different properties file for different environments.

You might want to create different properties files in the format like application-{profile}.properties, so you might end up creating something like this.

To access the, say now you will need to use
@Profile("dev") at the class level

The following code will fetch the and

For accessing say you have to use @Profile("prod") at class level

Access the properties in controller

To access the properties in controller, all you have to do is to use the @Value annotation

Hope,it helps !!

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *