Maven | Using Properties defined in pom.xml in .properties file

|
| By Webner

We are working on a web application built in spring MVC. We have some resources inside src/main/resources folder (Maven Project). The resources are Property files with data in the form of key-value pairs. We are using maven property placeholder syntax (${…}) inside properties files to use property values defined in pom.xml file. But it was not working.

Inside pom.xml file:

<properties>
<bv.env>dev</bv.env>
</properties>

Inside Properties file (/src/main/resources):

master.password.file=master.pasword.${bv.env}

We were getting following errors while trying to run the project:

value master.password.${bv.env}
PropertyLoader:loadXMLPropertyFile - cls: class com.mm.gbd.security.SecureStore , error loading filename
MMException [mmError=IO_EXCEPTION, objs=null]
at com.mm.gbd.security.PropertyLoader.loadXMLPropertyFile(PropertyLoader.java:197)
at com.mm.gbd.security.SecureStore.readFromMasterProperties(SecureStore.java:52)
at com.mm.gbd.security.SecureStore.main(SecureStore.java:169)
MMException [mmError=IO_EXCEPTION, objs=null]
at com.mm.gbd.security.PropertyLoader.loadXMLPropertyFile(PropertyLoader.java:225)
at com.mm.gbd.security.SecureStore.readFromMasterProperties(SecureStore.java:52)
at com.mm.gbd.security.SecureStore.main(SecureStore.java:169)

On checking the contents inside .war file we found that property placeholder variables were not getting replaced with actual values.

After some research we found that filtering flag was missing in section in pom.xml.

Filtering is basically used to find and substitute values for the variables with actual values. These variables in ${…} syntax can come from the system properties, your project properties, from your filter resources or from the command line.

So we have added following code to pom.xml file and after that everything works fine:

<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>

Some Important Points regarding Filtering:

1. If there are binary files Like pdf, certificates, jpg etc Inside your resources, just exclude them because maven filtering will corrupt them. (Maven uses totally different character encoding than the one used by files.)

2. Define properties inside pom file and use those as placeholders inside submodules. In future, it makes your project more flexible to adapt to changes regarding configurations, database connections etc.

3. In maven src/main/resources is the default folder for resource files. But you can also specify the different location for your maven resources using maven resource plugin tags.

Leave a Reply

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