Saturday, December 9, 2017

Mule: Load Properties as per the Environment (With Default Properties File)

It has been a best practice to load the properties file as per the environment, instead of some manual copy/paste or other techniques to do it.
Today, I will walk you through a MuleSoft application which uses the properties file as per the environment. When you wan to the run application in a dev runtime/environment, your application should pick up the dev environment properties file. Also, sometimes there is a requirement that we should have a common/default properties file which will hold common properties for all environments.

Steps

You can download the sample code from GitHub.
You can create a sample hello world application using the below steps:
Open Anypoint Studio -> file -> new -> MuleSoft project.Image title
Give the project name "helloworld" and click on finish.
The project structure will look like this:Image title
Create an HTTP endpoint, drag and drop the HTTP component, and configure it as shown below:Image title
Once the HTTP component is set, add set payload component and provide the below payload:
 ${hello} ${test} 
The hello and test key will be filled by the properties file value.
Add the dev.properties file to the src/main/resources folder as below:Image title
Add properties key=value in the dev.properties file, which will be picked up by set payload component at runtime.
Run the application with the argument as  -Dmule.env=dev . This will run the application as it is running in the development environment and will pick up the dev.properties file.
Once the application is deployed successfully, (check the console if the application deployed properly or not), go to the browser  and hit http://localhost:9090/. It will give you the response "hello."
Now I have a requirement that the test key is common to all environments and should be defaulted to default/common properties file.
Add the my-dev.properties file with the below content:
hello=local hello
test=local test
Add the below configuration in the helloworld.xml file for the load default property file as well as the environment specific properties file (remove if any Spring bean property placeholder configuration is available):
<spring:beans>
<context:property-placeholder
location="classpath:my-dev.properties,
classpath:${mule.env}.properties" />
</spring:beans>

Run the application with a dev environment:
Image title
Once the application is deployed, hit http://localhost:9090/ in the browser and you will see that the test key value is coming from a common file while hello world is overriden and coming from the dev.properties file.
References:

2 comments: